首页 文章

在golang中作为 Map 字段插入 Map

提问于
浏览
1

我正在尝试创建一个结构,其中一个字段是一个 Map . 但是,我无法使用方法初始化它,然后使用其他方法插入值 . 它报告错误

恐慌:在零 Map 中分配

来自Python背景,我对我错过的内容感到困惑 .

这是目标操场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()
    }
    

    参考:

    Should I define methods on values or pointers?

相关问题