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
- Map Internals
- Checking Existence
- Maps as Sets
- Iteration and Ordering