-
Notifications
You must be signed in to change notification settings - Fork 162
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
不要向nil map写入(panic: assignment to entry in nil map) #7
Comments
解答了我的疑惑,thanks |
不客气,很高兴这里的内容能有帮助 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
golang中map是引用类型,应用类型的变量未初始化时默认的zero value是nil。直接向nil map写入键值数据会导致运行时错误
panic: assignment to entry in nil map
看一个例子:
运行这段程序会出现运行时从错误:
因为在声明
alphabetMap
后并未初始化它,所以它的值是nil, 不指向任何内存地址。需要通过make
方法分配确定的内存地址。程序修改后即可正常运行:关于这个问题官方文档中解释如下:
同为引用类型的slice,在使用
append
向nil slice追加新元素就可以,原因是append
方法在底层为slice重新分配了相关数组让nil slice指向了具体的内存地址The text was updated successfully, but these errors were encountered: