Junior · Go foundations

Map order, nil maps and concurrency

Can you rely on iteration order or read a map during a concurrent write?

Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.

EXAMPLE · FRAGMENT UNLESS A COMPLETE PROGRAM IS SHOWN

go
score, ok := scores[id]
if !ok {
    // Handle missing separately from a valid zero score.
}
Reveal a strong answer
  1. Map iteration order is unspecified. Tests or output requiring stable order must sort keys or use an explicitly ordered representation. A nil map can be read and has length zero, but assignment requires an initialized map.

  2. Ordinary maps do not support unsynchronized concurrent read/write access. Protect the whole invariant with a lock, publish immutable snapshots, or choose a specialized concurrent structure for a measured use case.

  3. A map lookup can return a zero value for either a missing key or a present zero. Use the comma-ok result when that distinction matters. Deleting a key does not promise immediate shrinking of all backing memory.

Common trap

Several readers are safe only while no goroutine writes without the required synchronization.

Try it

A map[string]int contains a real score0. How do you distinguish it from an absent user?

Worked solution

Use value, ok := scores[id]. The value0 alone is ambiguous. For deterministic output, copy keys and sort them; do not infer insertion order from a few test runs.

Change the constraint

Why can sync.Map be a poor replacement for several map operations that must be atomic together?

How did you do?

Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.

Not marked. Progress stays on this browser, separate from course completion.

Primary references

Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.