How to iterate over slices in Go

At some point in most programs, you may have the need to iterate over a slice to perform some work. In Go, the range keyword is used within a for loop construct to iterate over slices.

Here’s how to iterate over a slice in Go using a for..range loop:

package main

import (
	"fmt"
)

func main() {
	var numbers = []int{1, 10, 100, 345, 1280}
	for i, v := range numbers {
		fmt.Printf("index: %d, value: %d\n", i, v)
	}
}
Run code snippet on the Go playground
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)
}

Thanks for reading, and happy coding!