Start learning free

LESSON 116 OF 671 · ARRAYS I

Maps and the ok Idiom in Go

Lesson

A map is Go's built-in dictionary: it stores key: value pairs and finds a value by its key instantly. The type map[string]int reads left to right as "keys are strings, values are ints". The easiest way to create one is a map literal, which creates and fills the map in a single line:

scores := map[string]int{"Alice": 92, "Bob": 77}
fmt.Println(scores["Alice"])   // prints 92
scores["Bob"] = 80             // update a value

One warning before we go on: a map that is only declared (var scores map[string]int) is nil — reading from it is fine, but writing into it stops your program with this exact panic:

panic: assignment to entry in nil map

Always create maps with a literal {...} or with make(map[string]int).


The trap:

In many languages, asking a dictionary for a key it doesn't have crashes (Python raises KeyError) or returns a special "nothing" value. Go does neither. Look up a missing key and you silently get the value type's zero value — 0 for numbers, "" for strings, false for bools:

fmt.Println(scores["Carol"])   // Carol isn't in the map...
// output: 0                   // ...no crash, no error — just 0

That 0 is a trap: did Carol score zero points, or is Carol simply not in the map? The lookup alone cannot tell you, and this silent ambiguity causes real bugs.

The fix — the "comma ok" idiom: a map read can return a second value, a bool that is true only if the key was actually present:

score, ok := scores["Carol"]
if !ok {
    fmt.Println("Carol is not in the map")
}

By convention that variable is named ok — you will see v, ok := m[key] everywhere in real Go code.


Assignment
Follow the Coding Tutorial to look up one present key and one missing key, printing the value and the ok flag both times:

  • Create scores := map[string]int{"Alice": 92, "Bob": 77}.
  • Look up "Alice" with aliceScore, ok := scores["Alice"] and print both values.
  • Look up "Carol" (who is not in the map) with carolScore, ok := scores["Carol"] and print both values — note the zero value and ok = false.

The exact expected output is:

aliceScore = 92 ok = true
carolScore = 0 ok = false

Hint
Print with fmt.Println("aliceScore =", aliceScore, "ok =", ok) — Println inserts a space between arguments. The second lookup can reuse ok with := because carolScore is a new variable.


STEP 1 OF 5
    Ctrl + Enter to check