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 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?

Answers


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).


Need Your Help

How to make Patch-able/Update-able application?

c# .net installer patch

I have completed a student project, this project extract data from xml files on internet and save to database and displays it. And i use that data in a few different ways e.g. display on main page,...

Empty span has height in Firefox

javascript jquery firefox

I'm a little surprised of strange behaviour of Firefox