Go Snippet

Iterating a Map in Go

Difficulty: Easy

Maps in Go are unordered: each program run randomises the iteration order to discourage code that relies on it. This snippet shows the basic `for key, value := range m` form, the comma-ok idiom for safe lookup, and the canonical pattern for iterating in sorted order. Internalise these three and you avoid the most common map bugs.

Code Snippets
/

Iterating a Map in Go

Iterating a Map in Go

Maps in Go are unordered: each program run randomises the iteration order to discourage code that relies on it. This snippet shows the basic `for key, value := range m` form, the comma-ok idiom for safe lookup, and the canonical pattern for iterating in sorted order. Internalise these three and you avoid the most common map bugs.

Go
Easy
3 snippets
go-maps
data-structures
iteration-patterns

1,191 views

21

for k, v := range m iterates over key/value pairs; drop , v if you only want keys, drop k, if you only want values (or use for _, v := range m). The runtime deliberately randomises the order each iteration to keep maps a black box, so any code that depends on order is buggy by definition. len(m) is O(1) and reports the current number of entries. Modifying the map during iteration is allowed but visiting newly added keys is unspecified; deleting the current key is safe.