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

huangapple go评论86阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2015年9月29日 07:24:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/32833297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定