typestar

The maps package in Go

Iterating a map's keys and values without writing the loop.

func mapHelpers() ([]string, int, bool) {
    steps := map[string]int{"basics": 39, "traits": 19, "errors": 15}

    keys := slices.Collect(maps.Keys(steps))
    slices.Sort(keys)

    total := 0
    for value := range maps.Values(steps) {
        total += value
    }

    copied := maps.Clone(steps)
    delete(copied, "errors")
    return keys, total, maps.Equal(steps, copied)
}

How it works

  1. maps.Keys returns an iterator, not a slice.
  2. slices.Collect turns that iterator into a slice.
  3. maps.Clone and maps.Equal do the obvious things.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
338
Tokens
99
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 57 seconds.

Type this snippet

Step 2 of 5 in Collections & text, step 10 of 26 in Standard library & project layout.

← Previous Next →