Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
package main
import "fmt"
func main() {
var m map[string]int
fmt.Println(len(m))
m["a"] = 1
fmt.Println(m)
}Prints 0, then panics
- Expecting
map[a:1], as if the first write created the map: a declaredmapisnil, and writing to it panics withassignment to entry in nil map. - Expecting
len(m)to panic: reading anilmap is safe, it behaves as an empty map, solen(m)is0and the panic comes only on the write.
- How would you change the declaration of
mso that the write works? - What does
m["x"]return whenmis anilmap?