Assignment to entry in nil map

yourbasic.org/golang

Why does this program panic?

var m map[string]float64
m["pi"] = 3.1416
panic: assignment to entry in nil map

Answer

You have to initialize the map using the make function (or a map literal) before you can add any elements:

m := make(map[string]float64)
m["pi"] = 3.1416

See Maps explained for more about maps.

Share this page: