Is it possible to declare a map at the package level in golang?

I want to make a global map. I am trying the following

package main

import "fmt"

globalMap := make(map[string]string)

func main() {
    globalMap["a"] = "A"
    fmt.Println(globalMap)
}

This gives me the following compilation error on line globalMap := make(map[string]string):

expected declaration, found 'IDENT' mas
non-declaration statement outside function body

Looking at the error, I understand that it will not allow me to create a global map. What could be the best way to create a global map?

Thank you

+4
source share
1 answer

You cannot use syntax :=outside the function body, but you can use the syntax for declaring a normal variable:

var globalMap = make(map[string]string)
+16
source

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


All Articles