What does the underscore(_) do in for loop Golang?

Issue

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!

Solution

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.

Answered By – mkopriva

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.