
Venter C.
—I don’t know how to use a for-each loop to iterate through a slice or an array in Go.
Go does not have a native for-each loop like some other languages, but you can achieve the same functionality using the range keyword. The range keyword allows you to iterate over arrays, slices, maps, and strings.
An array is a fixed-size collection of elements, while a slice is a more flexible, dynamic-sized collection in Go. The range keyword allows you to loop over these collections and access each element.
Create a for loop with the range keyword to iterate over an array or slice:
package main import "fmt" func main() { nums := []int{10, 20, 30, 40, 50} for index, value := range nums { fmt.Printf("Index: %d, Value: %d\n", index, value) } }
In each iteration of the loop, the index variable is assigned the value of the current element’s index, and the value is assigned the element itself.
The output will be:
Index: 0, Value: 10 Index: 1, Value: 20 Index: 2, Value: 30 Index: 3, Value: 40 Index: 4, Value: 50
Sometimes, you may not need the index and only care about the values in the collection. You can ignore the index using an underscore _:
for _, value := range nums { fmt.Println(value) }
The output will be:
10 20 30 40 50
Maps in Go store key-value pairs. Using range allows you to loop over both the keys and the values. This is equivalent to a for-each loop that iterates over dictionaries in other languages.
package main import "fmt" func main() { fruits := map[string]int{ "apple": 5, "banana": 7, "cherry": 12, } for key, value := range fruits { fmt.Printf("Fruit: %s, Quantity: %d\n", key, value) } }
On each iteration through the fruits map, the key variable is assigned the map key (for example, “apple”), and value is assigned the corresponding value (for example, 5)
The output will be:
Fruit: apple, Quantity: 5 Fruit: banana, Quantity: 7 Fruit: cherry, Quantity: 12
If you only need the keys or values, you can use an underscore _ to ignore the part you don’t need:
// Iterating only over keys for key := range fruits { fmt.Println(key) } // Iterating only over values for _, value := range fruits { fmt.Println(value) }
The keys-only output will be:
apple banana cherry
The values-only output will be:
5 7 12
slices packageTasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
