capypad
0 day streak
go / beginner
Snippet

Range Iteration Over Slices

The `range` keyword iterates over slices and maps. It returns two values: index and element. The blank identifier `_` is used when you don't need a value, telling Go to discard it.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
 
import "fmt"
 
func main() {
fruits := []string{"apple", "banana", "cherry"}
for index, fruit := range fruits {
fmt.Printf("%d: %s\n", index, fruit)
}
// Using underscore to ignore index
for _, fruit := range fruits {
fmt.Println(fruit)
}
}
Breakdown
1
for index, fruit := range fruits
Range returns index and value for each element in the slice
2
fmt.Printf("%d: %s\n", index, fruit)
Prints formatted string with index as %d and string as %s
3
for _, fruit := range fruits
Underscore discards the index, keeping only the value