panic: assignment to entry in nil map

转载自:https://github.com/kevinyan815/gocookbook/issues/7
golang中map是引用类型,应用类型的变量未初始化时默认的zero value是nil。直接向nil map写入键值数据会导致运行时错误

panic: assignment to entry in nil map

看一个例子:

package main
const alphabetStr string = "abcdefghijklmnopqrstuvwxyz"
func main() {
  var alphabetMap map[string]bool
  for _, r := range alphabetStr {
    c := string(r)
    alphabetMap[c] = true
  }
}

运行这段程序会出现运行时从错误:

panic: assignment to entry in nil map

因为在声明alphabetMap后并未初始化它,所以它的值是nil, 不指向任何内存地址。需要通过make方法分配确定的内存地址。程序修改后即可正常运行:

package main
import "fmt"
const alphabetStr string = "abcdefghijklmnopqrstuvwxyz"
func main() {
  alphabetMap := make(map[string]bool)
  for _, r := range alphabetStr {
    c := string(r)
    alphabetMap[c] = true
  }
  fmt.Println(alphabetMap["x"])
  alphabetMap["x"] = false
  fmt.Println(alphabetMap["x"])
}

关于这个问题官方文档中解释如下:

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.

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值