Go · Stage 5 – Grouping Data · Lesson 35 of 64

Looping with range

Visit each item in a slice or map.

Go code

names := []string{"Maya", "Noah"}
for index, name := range names {
    fmt.Println(index, name)
}
Line-by-line explanation
  1. A slice is created.
  2. Range visits each item.
  3. Index and name receive the current pair.
  4. Both are displayed.
Expected output
0 Maya
1 Noah

This is the expected result.

Use the blank identifier _ when one returned value is not needed.