Map Keys

May 11, 2023

The only restriction on map keys is that they must be comparable. The spec explains:

Map types

The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice. If the key type is an interface type, these comparison operators must be defined for the dynamic key values; failure will cause a run-time panic.

map[string]int
map[*T]struct{ x, y float64 }
map[string]interface{}

So in summary, virtually any non-interface type is a valid map key, except functions, slices, or other maps. Use of such an unsupported type will result in a compilation error.

func main() {
	var x map[map[string]string]string
	fmt.Println(x)
}

When compiled:

./test.go:8:12: invalid map key type map[string]string

If the map key is an interface type, then the individual interface values must be comparable, or a runtime panic will occur.

func main() {
	x := map[any]string{}
	x[func() {}] = "func"
	fmt.Println(x)
}

when executed:

panic: runtime error: hash of unhashable type func()

Quotes from The Go Programming Language Specification Version of December 15, 2022


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe