typestar

Maps in Go

Key-value storage and the comma-ok idiom.

func mapBasics() (int, bool, int) {
    scores := map[string]int{"ada": 95, "grace": 88}
    scores["kay"] = 92

    ada := scores["ada"]
    value, ok := scores["alan"]
    delete(scores, "grace")

    total := 0
    for _, score := range scores {
        total += score
    }
    return ada, ok, total + value
}

How it works

  1. A literal or assignment populates the map.
  2. value, ok := m[k] reports whether the key existed.
  3. delete removes; range iterates.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
269
Tokens
78
Three-star pace
90 tpm

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

Type this snippet

Step 4 of 9 in Arrays, slices & maps, step 19 of 30 in Language basics.

← Previous Next →