typestar

Working a map in Go

The comma-ok read, delete, and the deliberate randomness of iteration.

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

    missing, ok := steps["nope"]
    delete(steps, "errors")
    steps["cli"] = 12

    keys := make([]string, 0, len(steps))
    for key := range steps {
        keys = append(keys, key)
    }
    sort.Strings(keys)

    return missing + len(steps), ok, keys
}

How it works

  1. A missing key returns the zero value, so ask with two results.
  2. delete is a no-op on a key that is not there.
  3. Iteration order is randomised on purpose; sort the keys.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
326
Tokens
102
Three-star pace
90 tpm

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

Type this snippet

Step 5 of 9 in Arrays, slices & maps, step 20 of 30 in Language basics.

← Previous Next →