You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 07:10:58