英文:
Is it possible to declare a map at package level in golang?
问题
我想创建一个全局地图。我正在尝试以下代码:
package main
import "fmt"
var globalMap = make(map[string]string)
func main() {
globalMap["a"] = "A"
fmt.Println(globalMap)
}
在globalMap := make(map[string]string)
这一行,它给我返回以下编译错误:
expected declaration, found 'IDENT' mas
non-declaration statement outside function body
根据错误信息,我理解它不允许我创建一个全局地图。那么创建全局地图的最佳方法是什么?
谢谢。
英文:
I want a make global map. I am trying the following
package main
import "fmt"
globalMap := make(map[string]string)
func main() {
globalMap["a"] = "A"
fmt.Println(globalMap)
}
It gives me 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 it won't allow me to create a global map. what could the best way to create a global map ?
Thanks.
答案1
得分: 25
你不能在函数体外使用:=
语法,但你可以使用普通的变量声明语法:
var globalMap = make(map[string]string)
英文:
You can’t use the :=
syntax outside a function body, but you can use the normal variable declaration syntax:
var globalMap = make(map[string]string)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论