Middle · Go foundations
Comparability and map keys
Why can using any as a map key panic?
Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.
Reveal a strong answer
Map keys require a comparable key type. Arrays and structs are comparable only when their components are; slices, maps and functions are not generally comparable except their permitted nil comparisons.
An interface value is comparable when its dynamic value is comparable. A map[any]int can therefore compile but panic when used with a slice as the dynamic key. A generic comparable constraint has its own language rules; do not assume it validates arbitrary dynamic data recursively.
Choose stable, explicit key types. If semantic equality involves slices or normalized text, define canonicalization or hashing with collision handling and preserve the original equality contract.
Common trap
The static type any does not make every dynamic key valid for hashing or equality.
Try it
What happens with keys[[]int{1,2}] = 3 in a map[any]int?
Worked solution
It panics because the interface contains an unhashable slice. Use a comparable domain key, such as a fixed array where appropriate, or an explicitly encoded canonical key with documented semantics.
Change the constraint
What happens when a struct key contains a float64 NaN?
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.