Coding/Learn/go/go maps and hash tables
Go Foundational Course
01.Introduction, Toolchain & Package main
02.Variables, Zero Values, Constants & iota
03.Control Flow: If with Init Statements & Switch
04.The Unified For Loop & Range Iteration
05.Functions, Multiple Return Values & Named Returns
06.Arrays vs Slices: Dynamic Memory & Headers
07.Maps: Key-Value Hash Tables & Safe Access
08.Pointers & Value vs Pointer Semantics
09.Structs, Receiver Methods & Composition
10.Implicit Interfaces & Duck Typing with Typesafety
11.Explicit Error Handling, Wrapping & Inspection
12.Defer, Panic & Recover: Resource Cleanup
13.Strings, Runes & UTF-8 Encoding Internals
14.Goroutines & The M:N Work-Stealing Scheduler
15.Channels: CSP Concurrency & Pipelines
16.Select Statement, Non-Blocking IO & Timeouts
17.Mutexes, RWMutex & Atomic Primitives
18.Context Propagation, Cancellation & Deadlines
19.JSON Serialization, Tags & net/http Routing
20.Capstone: High-Performance Concurrent Microservice Engine
Course Certificate0%

Complete all lessons to earn

LearnMaps: Key-Value Hash Tables & Safe Access
7 / 20 0%
Lesson 07 of 20
12 mins read

Maps: Key-Value Hash Tables & Safe Access

PreviousNext Lesson
In Plain English

Maps provide O(1) key-value lookup. Learn initialization with make(), safe existence checking with the comma-ok idiom, and why map iteration order is deliberately randomized in Go.

The Mental Model

"A map is like a hotel mail cubby wall. Each room number (key) has a slot containing guest messages (value). Looking up room 404 is instantaneous."

Deep Dive: How It Works

Hash Table Architecture: Implemented as hash buckets holding key-value pairs with O(1) average lookup.

The Comma-Ok Idiom: val, ok := m[key] distinguishes between a missing key and a key with zero value.

Uninitialized Nil Maps: Reading a nil map returns zero value, but writing to a nil map triggers a runtime panic.

Syntax Blueprint

m := make(map[string]int)
m["zen"] = 100
val, ok := m["zen"]
delete(m, "zen")

Create map with make, assign key-values, inspect existence with comma-ok, delete keys with delete().

PointCore Rules to Remember

Point star
Comma-Ok Idiom: Always use val, ok := m[key] when zero values are valid map payload values.
Point star
Reference Semantics: Passing a map to a function shares the underlying hash table pointer.
Point star
Non-Deterministic Iteration: for k, v := range m randomizes order across executions to prevent bucket order dependency.

Common Beginner Traps & How to Fix Them

Mistake:Writing to an uninitialized nil map: var m map[string]int; m["key"] = 1.

Why it happens: A nil map header has no allocated hash bucket table.

How to fix: Initialize with make(map[string]int) or a map literal map[string]int{}.

Pro Tip: If sorted iteration is needed, collect keys into a slice, sort with sort.Strings() or slices.Sort(), and iterate over the keys.

Live Interactive Example

Hit Run Code to see it live
Word Frequency & Comma-Ok Inspection
Go 1.22 / Runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Output Console
Click "Run Code" to view the rendered output.
How it works: The comma-ok pattern distinguished between "mouse" (exists with count 0) and "keyboard" (does not exist).

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Count Character Frequencies

  • PointWrite a function charCounts(text string) map[rune]int.
  • PointIterate over text runes and tally their occurrences in a map.
  • PointIn main(), call charCounts("golang") and print the count of rune 'g'.
1
2
3
4
5
6
7
8
9
10
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates