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:
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:
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:
Thanks for reading, and happy coding!