Sentry Answers>Go>

Go For Each Loops

Go For Each Loops

Venter C.

The Problem

I don’t know how to use a for-each loop to iterate through a slice or an array in Go.

The Solution

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.

Iterating Over Arrays and Slices

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:

Click to Copy
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:

Click to Copy
Index: 0, Value: 10 Index: 1, Value: 20 Index: 2, Value: 30 Index: 3, Value: 40 Index: 4, Value: 50

Ignoring the Index

Sometimes, you may not need the index and only care about the values in the collection. You can ignore the index using an underscore _:

Click to Copy
for _, value := range nums { fmt.Println(value) }

The output will be:

Click to Copy
10 20 30 40 50

Iterating Over Maps

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.

Click to Copy
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:

Click to Copy
Fruit: apple, Quantity: 5 Fruit: banana, Quantity: 7 Fruit: cherry, Quantity: 12

Iterating Only Over Keys or Values

If you only need the keys or values, you can use an underscore _ to ignore the part you don’t need:

Click to Copy
// 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:

Click to Copy
apple banana cherry

The values-only output will be:

Click to Copy
5 7 12

Further reading

  • SentryGo Error Tracking and Performance Monitoring
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,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.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.