A couple questions about https://play.golang.org/p/PdJqR-pSN58

For the first one, from the Go Tour (here’s the relevant section):

elem, ok = m[key]

If  `key`  is in  `m` ,  `ok`  is  `true` . If not,  `ok`  is  `false` .
If  `key`  is not in the map, then  `elem`  is the zero value for the map's element type.

So, in short, ok (or whatever you call the second value returned when accessing a map, which is a bool) tells you if the key is present or not.

In the second case, in Go if may start with a short statement before the condition check. This is almost equivalent to doing this:

v, ok := m[“Barnabas”]
if ok {
  fmt.Println(v)
}

I say almost because in the latter case ok is local to the function scope in which it is located, while in your case (when the statement is part of the if) ok is local to the if scope, i.e., it can’t be used after the if. Please refer to a previous post where I referred to this. Again, the Go Tour mentions this: https://tour.golang.org/flowcontrol/6

1 Like