0Pricing
Go Academy · Lesson

Iteration and Ordering

Handle random map order.

Iterating a Map

Use range to loop over a map, getting each key and value.

package main

import "fmt"

func main() {
	m := map[string]int{"a": 1, "b": 2}
	for k, v := range m {
		fmt.Println(k, v)
	}
}

Order Is Random

Map iteration order is not guaranteed. Go deliberately randomizes it. Running the same loop twice may print keys in different orders.

All lessons in this course

  1. Map Internals
  2. Checking Existence
  3. Maps as Sets
  4. Iteration and Ordering
← Back to Go Academy