Search⌘ K

The for range Construct

Explore how to use Go's for range construct to iterate through map keys and values. Understand that map iteration order is unpredictable and learn how to safely delete map entries while looping. This lesson helps you manage Go maps efficiently using loops.

We'll cover the following...

Explanation #

The following construct can also be applied to maps:

for key, value := range map1 {
  ...
}

The key is the key of the map, and the value is the value for the key. They are local variables only known in the body of the for statement. If you are only interested in the values, use the form:

for _, value := range map1 {
  fmt.Printf("Value is: %d\n", value)
}

To get only the keys, you can use:

for key := range map1 {
  fmt.Printf("Key is: %d\n", key)
}

The order in which ...