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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助