Today we’re finishing up our discussion of…
Index expressions
…
So far, we’ve discussed what index expressions are, and specific rules as they apply to:
Otherwise
a[x]is illegal.
But there are two more special cases to consider for maps:
An index expression on a map
aof typemap[K]Vused in an assignment statement or initialization of the special formv, ok = a[x] v, ok := a[x] var v, ok = a[x]yields an additional untyped boolean value. The value of
okistrueif the keyxis present in the map, andfalseotherwise.
This is particularly useful to distinguish between an existing value in a map that happens to be set to the zero value. Consider:
m := map[int]string{
1: "foo",
2: "",
}
x := m[1] // x == "foo"
y := m[2] // y == ""
z := m[3] // z == "", even though key 3 does not exist in the map
yy, ok := m[2] // y == "", ok == true
zz, ok := m[3] // z == "", ok == false
Assigning to an element of a
nilmap causes a run-time panic.
So while reading from a nil map is permitted, assignment to one is not.
var m map[int]int // m is of type map[int]int, but nil
x := m[3] // x == 0, but the expression is valid
m[3] = 12 // run-time panic
Quotes from The Go Programming Language Specification Version of August 2, 2023