I'm currently available for contract work & technical writing opportunities. Hire me

How to iterate over slices in Go

In most programs, you’ll need to iterate over a collection to perform some work. This article will teach you how slice iteration is performed in Go.

Using a for..range loop

Iterating over a Go slice is greatly simplified by using a for..range loop:

main.go
package main

import (
	"fmt"
)

func main() {
	numbers := []int{1, 10, 100, 345, 1280}
	for i, v := range numbers {
		fmt.Printf("index: %d, value: %d\n", i, v)
	}
}
Output
index: 0, value: 1
index: 1, value: 10
index: 2, value: 100
index: 3, value: 345
index: 4, value: 1280

If you need only the index without the value, you may initialise the loop with only one variable:

for i := range numbers {
	fmt.Printf("index: %d", i)
}

And if you need to ignore the index, you may use the blank identifier (_).

for _, v := range numbers {
	fmt.Printf("Value: %v", v)
}

Using a standard for loop

You can also use a standard for loop to iterate over a slice:

main.go
package main

import (
	"fmt"
)

func main() {
	numbers := []int{1, 10, 100, 345, 1280}
	for i := 0; i < len(numbers); i++ {
		fmt.Printf("index: %d, value: %d\n", i, numbers[i])
	}
}
Output
index: 0, value: 1
index: 1, value: 10
index: 2, value: 100
index: 3, value: 345
index: 4, value: 1280

Reverse the iteration of a slice

If you want to iterate over a slice in reverse, the easiest way to do so is through a standard for loop counting down:

main.go
package main

import (
	"fmt"
)

func main() {
	numbers := []int{1, 10, 100, 345, 1280}
	for i := len(numbers) - 1; i >= 0; i-- {
		fmt.Printf("index: %d, value: %d\n", i, numbers[i])
	}
}
Output
index: 4, value: 1280
index: 3, value: 345
index: 2, value: 100
index: 1, value: 10
index: 0, value: 1

Thanks for reading, and happy coding!