Assignment to entry in nil map
Why does this program panic?
var m map[string]float64 m["pi"] = 3.1416
panic: assignment to entry in nil map
You have to initialize the map using the
make function before you can add any elements:
m := make(map[string]float64) m["pi"] = 3.1416
A new, empty map value is made using the built-in function
make, which takes the map type and an optional capacity hint as arguments:The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added. The Go Programming Language Specification: Map types
make(map[string]int) make(map[string]int, 100)
See Maps in a nutshell for all about maps in Go.
Share this page: