Go Initialization operator, variables with scope - 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 on the first line in init()ie //nameMap = make(TNameMap), I get a panic at startup main()because it was nameMapnever initialized:

panic: runtime error: assignment to entry in nil map

But - if init()I writenameMap := make(TNameMap)

instead nameMap = make(TNameMap), I do not get any panic, but there is also no conclusion - the main()process just starts and ends.

I understand that if I use the initialization operator - nameMap := make(TNameMap)- I declared a new variable nameMapthat is bound only to the function init(), and therefore only the package level variable is available var nameMap TNameMap main(), which leads to the absence of output, since the package level vardoes not contain map data.

: panic ? main() var, - panic?

+4
1

Go:

- , , .

, nil, . , " nil". nameMap = make(TNameMap), , init ( ). init, Println , () nil.

, , , . ( , ), Println.

, nil, . , map[T]string "", a map[T]int 0 . (, val,ok := nilMap[key], ok ).

+3

Source: https://habr.com/ru/post/1530908/


All Articles