Mastering `for range` Loop: Iterating Collections in Go
95 views
In Go, iteration over collections such as arrays, slices, maps, or strings is commonly done using the for range loop. The for range loop provides a straightforward way to access both the index and the value of each element in the collection.
Examples of Using for range with Different Data Structures
1. Slices
package main
import (
"fmt"
)
func main() {
// Slice of integers
numbers := []int{1, 2, 3, 4, 5}
// Use `for range` to iterate over the slice
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
2. Arrays
package main
import (
"fmt"
)
func main() {
// Array of strings
fruits := [3]string{"Apple", "Banana", "Cherry"}
// Use `for range` to iterate over the array
for index, value := range fruits {
fmt.Printf("Index: %d, Value: %s\n", index, value)
}
}
3. Maps
package main
import (
"fmt"
)
func main() {
// Map of string keys to integer values
scores := map[string]int{
"Alice": 10,
"Bob": 20,
"Carol": 30,
}
// Use `for range` to iterate over the map
for key, value := range scores {
fmt.Printf("Key: %s, Value: %d\n", key, value)
}
}
4. Strings
package main
import (
"fmt"
)
func main() {
// String
s := "hello"
// Use `for range` to iterate over the string (interpreted as runes)
for index, runeValue := range s {
fmt.Printf("Index: %d, Rune: %c\n", index, runeValue)
}
}
Explanation of for range Loop
- Slices and Arrays: The
for rangeloop returns both the index and the value of each element. If you only need the value, you can use the blank identifier_to ignore the index.
for _, value := range numbers {
fmt.Printf("Value: %d\n", value)
}
- Maps: The loop returns the key and the value for each entry in the map. If you only need the keys or values, use the blank identifier
_to ignore the other.
// Iteration over map keys only
for key := range scores {
fmt.Printf("Key: %s\n", key)
}
- Strings: Iterates over each rune in the string, which is useful for handling Unicode characters. The loop returns the index of the rune and the rune itself.
Advanced Example with Structs
You might also want to iterate over a slice of structs. Here’s how you can do that:
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
// Slice of Person structs
people := []Person{
{Name: "Alice", Age: 30},
{Name: "Bob", Age: 25},
{Name: "Carol", Age: 35},
}
// Use `for range` to iterate over the slice of structs
for index, person := range people {
fmt.Printf("Index: %d, Name: %s, Age: %d\n", index, person.Name, person.Age)
}
}
By using the for range loop, you can easily iterate over different types of collections in Go. It provides a concise and readable syntax for accessing the elements, making your code clean and efficient.