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)
}
}
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!