4

I am just getting started learning the Golang language! In for loop, I saw sometimes adding an underscore or without underscore.

Whatever add _ or not, I got the same result.

package main

import (
    "fmt"
)

func main() {
    doSomething()
    sum := addValues(5, 8)
    fmt.Println("The sum is", sum)

    multiSum, multiCount := addAllValues(4, 7, 9)
    fmt.Println("multisum", multiSum)
    fmt.Println("multiCount", multiCount)
}

func doSomething() {
    fmt.Println("Doing Something")
}

func addValues(value1 int, value2 int) int {
    return value1 + value2
}

func addAllValues(values ...int) (int, int) {
    total := 0
    for _, v := range values {
        total += v
    }
    return total, len(values)
}
func addAllValues(values ...int) (int, int) {
    total := 0
    for v := range values {
        total += v
    }
    return total, len(values)
}

All I know is I don't care about the index. Is that all? or there is something more what I have to know??

I really appreciate your help!

JiwanJeon94
  • 385
  • 4
  • 12
  • 2
    The result is not the same though: it's `multisum 20` vs `multisum 3`. – bereal Feb 14 '22 at 07:34
  • Basically it is called the blank identifier which, in case of a for-loop, ignores the variable. Here is a thorough answer to your question: https://stackoverflow.com/a/27764432/4809932 – bajro Feb 14 '22 at 07:36
  • @bereal Oh yeah you're right... I missed a huge thing. When I check the result again, I got a different result. I'm still figuring out why I got different result – JiwanJeon94 Feb 14 '22 at 08:57
  • @bereal For now, I know why I got a different result! Thank you for pointing it out! – JiwanJeon94 Feb 14 '22 at 08:59
  • Does this answer your question? [What is "\_," (underscore comma) in a Go declaration?](https://stackoverflow.com/questions/27764421/what-is-underscore-comma-in-a-go-declaration) – Travis Britz Mar 28 '22 at 01:00

4 Answers4

7

For range over slices:

  1. In for v := range values { the v is the index of the element in the slice.
  2. In for _, v := range values { the v is the actual element value.
  3. In for i, v := range values { the i is the index and the v is the element.
  4. In for i, _ := range values { the i is the index of the element in the slice.

You can run this playground example to see the differences.


Range expression                          1st value          2nd value

array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
string          s  string type            index    i  int    see below  rune
map             m  map[K]V                key      k  K      m[k]       V
channel         c  chan E, <-chan E       element  e  E

For more details see the spec.

mkopriva
  • 35,176
  • 4
  • 57
  • 71
1

If you don't want to use the variable that iterates in the loop, you can use _ to simply let Go ignore it:

mySlice := [int]{1,3,4,59,5}
for _,x := range mySlice {
    fmt.Println(x)
}
ouflak
  • 2,458
  • 10
  • 44
  • 49
drainuzzo
  • 11
  • 3
0

By placing underscore you are telling the compiler this: Ok, I'm aware that this function is returning something but I don't care! For example:

package main

import "fmt"

func main() {
    mul1, add1 := test_function(2, 3)
    fmt.Println(mul1, add1)

    mul2, _ := test_function(4, 5)
    fmt.Println(mul2)

    _, add3 := test_function(7, 8)
    fmt.Println(add3)
}

func test_function(a int, b int) (mul int, add int) {
    return a * b, a + b
}
mrasoolmirza
  • 787
  • 1
  • 6
  • 22
0

just to add to the amazing answer above: I think one of the main benefits is to maintain readability in your program: if you replace the blank identifier with a variable then you have to use it or your program will not compile. also this decrease memory allocation be neglecting one of the returned parameters...

MSH
  • 395
  • 1
  • 4
  • 13