Iterating Collections with range
Using range over slices, maps and strings
What Is range?
range is a special form of the for loop that iterates over arrays, slices, maps, strings, and channels. It returns an index (or key) and a value on each iteration.
range Over a Slice
Returns the index and a copy of the element:
package main
import "fmt"
func main() {
fruits := []string{"apple", "banana", "cherry"}
for i, fruit := range fruits {
fmt.Printf("%d: %s\n", i, fruit)
}
}All lessons in this course
- Arrays: Fixed-Length Collections
- Slices: Dynamic Lists
- Maps: Key-Value Stores
- Iterating Collections with range