Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
func main() {
m := map[string]int{"a": 0}
v, ok := m["a"]
w, ok2 := m["b"]
fmt.Println(v, ok, w, ok2)
}0 true 0 false
- Expecting
okto befalsefor"a"because its value is0:oktells whether the key is in the map, and"a"is there. - Expecting a missing key to read as
-1: a missing key reads as the zero value of the value type, which is0forint.
- Why can't
m["b"] == 0alone tell you whether the key"b"exists? - How would you write an
ifthat runs only when the key is in the map?