Panic:assignment to entry in nil map
7月 23, 2020
参考以下代码,运行时会报 panic: assignment to entry in nil map。
package main
import "fmt"
func main() {
var m map[string]int
m["a"] = 1
fmt.Println(m["a"])
}
//panic: assignment to entry in nil map
查了一下原因,发现是通过 var m map[string]int
得到的值是 nil, 不指向任何内存地址。需要通过 make
方法才可以分配确定的内存地址。
这个问题官方博客中解释如下:
This variable m is a map of string keys to int values:
var m map[string]int
Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn’t point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don’t do that. To initialize a map, use the built in make function:
m = make(map[string]int)
同为引用类型的 slice,在使用 append
向 nil slice 追加新元素就可以,原因是 append
方法在底层为 slice 重新分配了相关数组让 nil slice 指向了具体的内存地址。
nil map doesn’t point to an initialized map. Assigning value won’t reallocate point address. The append function appends the elements x to the end of the slice s, If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.
同样的道理,结构体通过 var
初始化并赋值也会报 Panic:
package main
type ListNode struct {
Value int
Next *ListNode
}
func main() {
var head *ListNode
head.Value = 10
}
// panic: runtime error: invalid memory address or nil pointer dereference
var 没有初始化结构体的实例,故没有地址,所以在给 head.value
赋值的时候触发了 nil pointer
的 panic。