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!
For range over slices:
for v := range values { the v is the index of the element in the slice.for _, v := range values { the v is the actual element value.for i, v := range values { the i is the index and the v is the element.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With