Welcome To Golang By Example

Go: Different ways of iterating over an Array and Slice

Go provides many different ways of iterating over an array. All examples below are also applicable to slice.

Let’s define an array of letters first

letters := []string{"a", "b", "c", "d", "e"}

Using the range operator

for i, letter := range letters {
   fmt.Printf("%d %s\n", i, letter)
}
for _, letter := range letters {
   fmt.Println(letter)
}
for i := range letters {
   fmt.Println(i)
}
i := 0
for range letters {
  fmt.Println(i)
  i++
}

Using Only For operator

len := len(letters)
for i := 0; i < len; i++ {
  fmt.Println(letters[i])
}
len := len(letters)
for i, j := 0, len; i < j; i, j = i+1, j-1 {
  fmt.Println(letters[i])
}