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
?