duanmi1900 2014-03-10 04:02
浏览 30
已采纳

Go初始化运算符,封装范围变量-混淆:

The following code works correctly - output: You chose Test 1

package main

import (
    "fmt"
)

type TNameMap map[int]string

var nameMap TNameMap

func init() {

    nameMap = make(TNameMap)
    nameMap[1] = "You chose Test 1"
    nameMap[2] = "You chose Test 2"
    nameMap[3] = "You chose Test 3"

}

func main() {

    fmt.Println(nameMap[1])

}

If I comment out the first line in init() i.e //nameMap = make(TNameMap) , I get a panic when main() runs, because nameMap was never initialized:

panic: runtime error: assignment to entry in nil map

But - if in init() I write nameMap := make(TNameMap)

instead of nameMap = make(TNameMap) , I get no panic, but also no output - main() simply runs and process terminates.

I understand that if I use the Initialization operator - nameMap := make(TNameMap) - I have declared a new variable nameMap that is scoped only to the init() function and so only the package level variable var nameMap TNameMap is in scope for main(), resulting in no output, because the package level var holds no map data.

But, I am confused: Why don't I get the panic in that situation? If main() is making the call on the package var, it was never initialized - so why no panic?

  • 写回答

1条回答 默认 最新

  • duanjian7343 2014-03-10 04:24
    关注

    According to the Go spec:

    A nil map is equivalent to an empty map except that no elements may be added.

    This means that you can read from a nil map, but not write. Just like the panic says "assignment to entry in nil map". If you comment out just the line nameMap = make(TNameMap) it will crash because you attempt to write to it in init (which is where the panic happens). If you comment out the entirety of init the Println will not crash because you're permitted to access (read from) a nil map.

    Changing the assignment to a declaration is just masking the real issue here, what's happening is it's making all the assignments valid, and then discarding the result. As long as you make the assignments valid (either by removing them or making a temporary variable), then you will observe the same behavior in Println.

    The value returned by a nil map is always the zero value of the value type of the map. So a map[T]string returns "", a map[T]int returns 0, and so on. (Of course, if you check with val,ok := nilMap[key] then ok will be false).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测