Insert into a map as a field of map in golang

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

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:

Should I define methods on values or pointers?

huangapple
  • 本文由 发表于 2017年6月6日 11:14:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/44380836.html
匿名

发表评论

匿名网友

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

确定