Golang for-range Loop

Last Updated: September 13, 2022

Go language for-range loop is to iterate over a collection of items

Iterate over Array in GO

traffic := [4]string{"Sunday", "Monday", "Tuesday", "Wednesday"}

for i, v := range traffic {
  fmt.Println(i, v)
}

Output

0 Sunday
1 Monday
2 Tuesday
3 Wednesday

If you do not need the 

If you do not need to deal with index then you can use

 for _, v := range traffic {
    fmt.Println(v)
}

If you need only index then:

 for i, _ := range traffic {
    fmt.Println(i)
}

Iterating over string using for-range

for pos, char := range "Hello, world!" {
    fmt.Println(pos, char)
}

Output

Go Programming Language for Dummies

0 72
1 101
2 108
3 108
4 111
5 44
6 32
7 119
8 111
9 114
10 108
11 100
12 33

https://stackoverflow.com/questions/7782411/is-there-a-foreach-loop-in-go

Test