为什么在Go语言中从nil map读取值不会触发panic?
Go中nil map访问键为何不触发panic?
在Go语言里,对nil map执行键查找操作是完全合法的,不会触发panic,这是语言规范明确规定的行为:
- 当你通过
mp[key]访问nil map的键时,会返回该map值类型的零值。比如你的代码里map的值类型是int,零值就是0,所以mp["12"]会返回0,程序可以正常执行。 - 只有当你尝试向nil map写入键值对(比如
mp["12"] = 10)时,才会触发panic。
你的代码运行时,log.Println(mp["12"], "12")会输出0 12,之后才会执行到if mp == nil分支里的panic语句。
示例代码:
// You can edit this code! // Click here and start typing. package main import "log" func main() { var mp map[string]int = nil log.Println(mp["12"], "12") // works fine if mp == nil { panic("map is nil") // panic here } }
内容的提问来源于stack exchange,提问作者sion
相关产品推荐
相关产品推荐

