The for range Construct

This lesson explains how to use the for range construct to access key-value pairs in a map.

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 elements are visited when iterating over a map using a for range statement is unpredictable, even if the same loop is run multiple times with the same map. The first element in a map iteration is chosen at random. This behavior allows the map implementation to ensure better map balancing. Your code should not assume that the elements are visited in any particular order.

Implementation #

Here is an example of a program that uses a for loop on a map.

Get hands-on with 1200+ tech skills courses.