英文:
Insert into a map as a field of map in golang
问题
我正在尝试创建一个结构体,其中一个字段是一个映射(map)。然而,我无法使用一个方法进行初始化,然后使用另一个方法插入值。它报告错误:
panic: assignment to entry in nil map
作为一个来自Python背景的人,我对我错过了什么感到困惑。
以下是目标playground代码片段:
package main
type profile map[string]float64
type foobar struct {
foo profile
bar map[string]profile
}
func (fb foobar) Init() {
fb.foo = make(profile)
fb.bar = make(map[string]profile)
}
func (fb foobar) Set() {
fb.bar["foo1"] = make(profile)
}
func main() {
test := foobar{}
test.Init()
test.Set()
}
链接:https://play.golang.org/p/Vp3vl9Ow41
英文:
I am trying to create a struct, one of whose fields is a map. However, I cannot initialize it with a method and then insert a value with another method. It reports error
> panic: assignment to entry in nil map
Coming from a Python background, I am confused on what I missed.
Here is the goal playground snippet
package main
type profile map[string]float64
type foobar struct {
foo profile
bar map[string]profile
}
func (fb foobar) Init() {
fb.foo = make(profile)
fb.bar = make(map[string]profile)
}
func (fb foobar) Set() {
fb.bar["foo1"] = make(profile)
}
func main() {
test := foobar{}
test.Init()
test.Set()
}
答案1
得分: 4
Init
方法的接收者(fb foobar)
是一个值。它应该是一个指针(fb *foobar)
。例如,
package main
type profile map[string]float64
type foobar struct {
foo profile
bar map[string]profile
}
func (fb *foobar) Init() {
fb.foo = make(profile)
fb.bar = make(map[string]profile)
}
func (fb foobar) Set() {
fb.bar["foo1"] = make(profile)
}
func main() {
test := foobar{}
test.Init()
test.Set()
}
参考:
英文:
The Init
method receiver (fb foobar)
is a value. It should be a pointer (fb *foobar)
. For example,
package main
type profile map[string]float64
type foobar struct {
foo profile
bar map[string]profile
}
func (fb *foobar) Init() {
fb.foo = make(profile)
fb.bar = make(map[string]profile)
}
func (fb foobar) Set() {
fb.bar["foo1"] = make(profile)
}
func main() {
test := foobar{}
test.Init()
test.Set()
}
Reference:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论