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
but
An index expression on a map a of type map[K]V used in an assignment or initialization of the special form
v, ok := a[x]
yields an additional untyped boolean value.
I am still learning Go. Is it a "syntax feature" that is baked into a language and "just works when this syntax is used", i.e. calls to v := a[x]
and v, ok := a[x]
are represented as different types of nodes in AST like MapGetAndCheckExistsNode(m, k, v, ok)
vs MapGet(m, k, v)
? Or this is implemented using "normal" Go syntax and indexing function is somehow aware of whether it's output is later "destructured" or not? Is it possible to force index expression to return tuple or struct with s.v
and s.ok
fields using s := a[x]
syntax?
It’s an arbitrary rule as part of the language itself. It is used to avoid panics on typecasts:
t, ok := x.(T)
Or to check if a key really exists in a map:
v, ok := m[k]
Or to check a receive worked:
x, ok := <-ch
It’s not possible to do it with your own functions, only in these special cases inserted by the language designers. See the spec for more.