Index expressions for maps

November 15, 2023

Index expressions

For a of map type M:

  • x’s type must be assignable to the key type of M

No surprise here. The key must be assignable to the key type. But notably, it needn’t be of an identical type, so long as it is assignable to the key type.

m := map[string]int{
	"foo": 3,
	"bar": 12,

m[string("foo")] // string("foo") is explicitly of type string, so assignable.
m["foo"] // Untyped constant string "foo" is assignable to type `string`

type Key string
k := Key("bar")
m[k] // k is of type Key, not assignable to type string without explicit conversion
  • if the map contains an entry with key x, a[x] is the map element with key x and the type of a[x] is the element type of M

This should be intuitive.

v := m["bar"] // v has value 12, and is of type int
  • if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M

An empty map (eg map[string]int{}) and a nil map behave the same when attempting to reference values stored within. And whether empty, nil, or the requested key simply doesn’t exist in a populated map, the result is the zero value of the map’s element type:

m := map[string]int{"foo":123}
n := map[string]int{}
var o map[string]int // nil map

fmt.Println(m["x"], n["x"], o["x"]) // Prints: 0 0 0

Quotes from The Go Programming Language Specification Version of August 2, 2023

Share this

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

Unsure? Browse the archive .