What is for range in Go: Explanation and Examples
for range is a special loop that lets you easily go through elements in arrays, slices, maps, strings, or channels. It returns the index and value of each element one by one, making it simple to process collections without manual counting.How It Works
The for range loop in Go works like a conveyor belt that hands you each item in a collection one at a time. Imagine you have a basket of apples, and you want to look at each apple without counting them yourself. The for range loop automatically gives you the position (index) and the apple (value) as you move along the basket.
Under the hood, Go handles the details of moving through the collection, so you can focus on what to do with each item. This makes your code cleaner and less error-prone compared to using a traditional loop with manual counters.
Example
This example shows how to use for range to print each fruit and its position in a slice.
package main import "fmt" func main() { fruits := []string{"apple", "banana", "cherry"} for index, fruit := range fruits { fmt.Printf("Fruit at position %d is %s\n", index, fruit) } }
When to Use
Use for range whenever you need to process each item in a collection like a list, map, or string. It is perfect for tasks like printing values, summing numbers, or filtering data.
For example, if you have a list of user names and want to greet each user, for range makes it easy to write clear and simple code without worrying about indexes or lengths.
Key Points
- for range loops over elements in arrays, slices, maps, strings, and channels.
- It returns two values: the index (or key) and the value of each element.
- You can ignore the index or value by using an underscore
_. - It simplifies looping and reduces errors compared to manual loops.