types - Go Initialization operator, package scoped variables - confused: -
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 comment out first line in init()
i.e //namemap = make(tnamemap)
, panic when main()
runs, because namemap
never initialized:
panic: runtime error: assignment entry in nil map
but - if in init()
write namemap := make(tnamemap)
instead of namemap = make(tnamemap)
, no panic, no output - main()
runs , process terminates.
i understand if use initialization operator - namemap := make(tnamemap)
- have declared new variable namemap
scoped init()
function , package level variable var namemap tnamemap
in scope main()
, resulting in no output, because package level var
holds no map data.
but, confused: why don't panic
in situation? if main()
making call on package var, never initialized - why no panic
?
according go spec:
a nil map equivalent empty map except no elements may added.
this means can read nil map, not write. panic says "assignment entry in nil map". if comment out line namemap = make(tnamemap)
crash because attempt write in init
(which panic happens). if comment out entirety of init
println not crash because you're permitted access (read from) nil map.
changing assignment declaration masking real issue here, what's happening it's making assignments valid, , discarding result. long make assignments valid (either removing them or making temporary variable), observe same behavior in println.
the value returned nil map 0 value of value type of map. map[t]string
returns ""
, map[t]int
returns 0
, , on. (of course, if check val,ok := nilmap[key]
ok
false).
Comments
Post a Comment