Skip to content
Maps
step 1/5

Reading — step 1 of 5

Learn

~2 min readCollections

Maps

A map is Go's built-in hash table: keys → values, constant-time lookup, and the data structure behind every "count things," "index by name," and "have I seen this before?" problem — including this lesson's exercise.

Making and using

go

One landmine before anything else: a nil map (declared but never made — var m map[string]int) reads fine but panics on write. If you create maps with make or a literal, you'll never meet this panic; if you ever see assignment to entry in nil map, you now know the cure.

The zero-value read (feature and trap)

Reading a missing key doesn't error — it returns the value type's zero value:

go

Trap: you can't tell "absent" from "stored zero." The comma-ok idiom answers that when it matters:

go

Feature: for counting, the zero-read is a gift — no existence check needed:

go

That one-liner is the counting idiom, and it's the engine of your exercise.

Iterating — in random order, on purpose

go

Go deliberately randomizes map iteration order — differently on every run — so nobody can accidentally depend on it. If output must be ordered (graders care!), collect the keys, sort them, then walk:

go

Map + sorted keys is a pattern pair — learn them as a unit.

Sets, while we're here

Go has no set type because a map is one: seen := make(map[string]bool), membership is seen[x], insertion is seen[x] = true. "Distinct" problems are exactly this.

Your exercise: Distinct Words

Count the distinct words in the input. The whole solution is this lesson in four moves: read words (fmt.Scan in a loop stops naturally at EOF — its error return says when input ran out), record each in a map (seen[word] = true), and print len(seen). Duplicates cost nothing — writing the same key twice stores it once, which is the entire point of a map. If you also want to practice comma-ok and counting, tally with map[string]int instead and notice len doesn't change; the map doesn't care how enthusiastically a key was inserted.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…