How to Iterate Over Slice in Go: Simple Examples and Tips
In Go, you can iterate over a slice using a
for loop with an index or a for range loop that gives both index and value. The for range loop is the most common and readable way to access each element in the slice.Syntax
There are two main ways to loop over a slice in Go:
- Using a classic for loop: You use an index to access each element.
- Using a for range loop: This gives you both the index and the value directly.
Example syntax:
for i := 0; i < len(slice); i++ {
value := slice[i]
// use value
}
for i, value := range slice {
// use i and value
}go
for i := 0; i < len(slice); i++ { value := slice[i] // use value } for i, value := range slice { // use i and value }
Example
This example shows how to print all elements of a slice using both the classic for loop and the for range loop.
go
package main import "fmt" func main() { fruits := []string{"apple", "banana", "cherry"} fmt.Println("Using classic for loop:") for i := 0; i < len(fruits); i++ { fmt.Println(i, fruits[i]) } fmt.Println("\nUsing for range loop:") for i, fruit := range fruits { fmt.Println(i, fruit) } }
Output
Using classic for loop:
0 apple
1 banana
2 cherry
Using for range loop:
0 apple
1 banana
2 cherry
Common Pitfalls
One common mistake is to use the for range loop but accidentally capture the loop variable's address inside a closure, which leads to unexpected results.
Also, forgetting that the range loop returns a copy of the element, not a reference, can cause bugs when modifying elements.
go
package main import "fmt" func main() { nums := []int{1, 2, 3} var ptrs []*int // Wrong: appending address of loop variable (same variable reused) for _, n := range nums { ptrs = append(ptrs, &n) } for _, p := range ptrs { fmt.Println(*p) // prints 3, 3, 3 instead of 1, 2, 3 } // Correct: use index to get address of slice element ptrs = nil for i := range nums { ptrs = append(ptrs, &nums[i]) } for _, p := range ptrs { fmt.Println(*p) // prints 1, 2, 3 } }
Output
3
3
3
1
2
3
Quick Reference
Tips for iterating over slices in Go:
- Use
for rangefor clean and readable code. - Remember
rangereturns a copy of the element, not a pointer. - Use classic
forloop if you need to modify elements by index. - Be careful when capturing loop variables inside closures.
Key Takeaways
Use for range loops to iterate over slices easily and readably.
Range returns copies of elements; use index if you need references.
Avoid capturing loop variables' addresses directly in closures.
Classic for loops give full control with indexes for modification.
Remember slice length with len(slice) when using classic loops.