我正在尝试将值分配给在init func中初始化的地图。
但恐慌发生了: 分配到零地图中的条目
package main
type Object interface {
}
type ObjectImpl struct {
}
type Test struct{
collection map[uint64] Object
}
func (test Test) init(){
test.collection = make(map[uint64] Object)
}
func main() {
test := &Test{}
test.init()
test.collection[1]=&ObjectImpl{}
}
答案 0 :(得分:2)
该函数将Test
作为值,因此它获得了自己的副本。函数返回时,test Test
的所有更改都将消失。用指针取Test
代替:
func (test *Test) init(){
test.collection = make(map[uint64] Object)
}
请注意,导出结构Test
,方法init
不是,因此您的库的用户可能会创建Test
但不能正确初始化它。似乎go社区已经建立了独立NewType
方法的惯例:
type test struct{
collection map[uint64] Object
}
function NewTest() *test {
return &test{
collection: make(map[uint64] Object),
}
}
这可确保用户只能通过调用test
获取NewTest
,并且会按预期进行初始化。
答案 1 :(得分:1)
您应该使用init
方法的指针接收器:
func (test *Test) init() { // use a pointer to test
test.collection = make(map[uint64] Object)
}
没有指针,您正在初始化test
对象副本的地图。实际的test
对象永远不会获得初始化的地图。