英文:
Create global map variables
问题
我需要一点关于在Go中创建全局地图变量的帮助。我已经做的如下所示:
package ...
import(
...
)
...
type ir_table struct{
symbol string
value string
}
var ir_MAP map[int]ir_table
由于我没有初始化地图,所以我得到了一个空指针解引用错误。我应该怎么做才能在全局范围内使用这个变量?或者,如果这不是正确的方法,请指导我。
英文:
I need a little help regarding creating a global map variable in Go. What I have done is as follows:
package ...
import(
...
)
...
type ir_table struct{
symbol string
value string
}
var ir_MAP map[int]ir_table
Since I am not initializing the map, I am getting a nil pointer dereference error. What must I do to use this variable globally? Or, if this is not a correct way to do this, please guide me.
答案1
得分: 50
你需要用一个空的映射来初始化它:
var ir_MAP = map[int]ir_table{}
或者,如“系统”建议的那样:
var ir_MAP = make(map[int]ir_table)
问题是映射的零值是nil,而你不能向nil映射中添加项目。
英文:
You need to initialize it with an empty map:
var ir_MAP = map[int]ir_table{}
or, as "the system" suggested:
var ir_MAP = make(map[int]ir_table)
The problem is that the zero value of a map is nil, and you can't add items to a nil map.
答案2
得分: 20
你可以直接像这样初始化一个map:
var Romans = map[byte]int{
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
英文:
You can directly initialize a map like this:
var Romans = map[byte]int{
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
答案3
得分: 10
你几乎做对了。你只是还没有初始化你的映射。
这是在The Playground中的可工作代码。
package main
import "fmt"
type ir_table struct{
symbol string
value string
}
// 定义全局映射;用尾随的{}初始化为空
var ir_MAP = map[int]ir_table{}
func main() {
ir_MAP[1] = ir_table{symbol:"x", value:"y"}
TestGlobal()
}
func TestGlobal() {
fmt.Printf("1 -> %v\n", ir_MAP[1])
}
英文:
You almost have it right. You just haven't initialized your map yet.
Here's working code in <a href="http://play.golang.org/p/4tL1Yff2LK">The Playground</a>.
package main
import "fmt"
type ir_table struct{
symbol string
value string
}
// define global map; initialize as empty with the trailing {}
var ir_MAP = map[int]ir_table{}
func main() {
ir_MAP[1] = ir_table{symbol:"x", value:"y"}
TestGlobal()
}
func TestGlobal() {
fmt.Printf("1 -> %v\n", ir_MAP[1])
}
答案4
得分: 9
旧话题,但最优雅的解决方案还没有被提到。
这在无法在主函数中分配值的模块中非常有用。init只执行一次,因此每次需要初始化地图时,它都可以节省一些CPU周期。
package main
import (
"fmt"
)
var (
globalMap = make(map[string]string)
)
func init() {
globalMap["foo"] = "bar"
globalMap["good"] = "stuff"
}
func main() {
fmt.Printf("globalMap:%#+v", globalMap)
}
英文:
old topic, but the most elegant solution hasn't been mentioned.
This is quite useful in modules where it's not possible to assign values in the main function. init is executed only once so it saves a few CPU cycles every time the map would have to be initialized otherwise.
https://play.golang.org/p/XgC-SrV3Wig
package main
import (
"fmt"
)
var (
globalMap = make(map[string]string)
)
func init() {
globalMap["foo"] = "bar"
globalMap["good"] = "stuff"
}
func main() {
fmt.Printf("globalMap:%#+v", globalMap)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论