The range
keyword in Go is a powerful tool for iterating over various data structures. It simplifies loops and provides a clean, readable syntax for traversing arrays, slices, maps, strings, and channels.
The general syntax of the range
keyword is:
for index, value := range collection {
// Use index and value
}
Depending on the type of collection, the range
clause returns different values:
One of the most common uses of range
is to iterate over arrays and slices. Here's an example:
fruits := []string{"apple", "banana", "cherry"}
for index, fruit := range fruits {
fmt.Printf("Index: %d, Fruit: %s\n", index, fruit)
}
This code will print the index and value of each element in the slice. If you don't need the index, you can use the blank identifier _
:
for _, fruit := range fruits {
fmt.Println(fruit)
}
The range
keyword is particularly useful for iterating over maps. It returns both the key and value for each entry:
ages := map[string]int{"Alice": 25, "Bob": 30, "Charlie": 35}
for name, age := range ages {
fmt.Printf("%s is %d years old\n", name, age)
}
When used with strings, range
iterates over Unicode code points (runes), not bytes:
for index, char := range "Hello, 世界" {
fmt.Printf("Index: %d, Character: %c\n", index, char)
}
The range
keyword can also be used to receive values from a channel until it's closed:
ch := make(chan int)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
}()
for num := range ch {
fmt.Println(num)
}
range
when you need to iterate over all elements in a collection.range
creates a copy of each element, so modifying the value variable won't affect the original collection.To further enhance your understanding of Go and its iteration capabilities, explore these related topics:
By mastering the range
keyword, you'll be able to write more concise and readable Go code, especially when working with collections and iterative tasks.