无法通过struct方法替换指针

问题描述 投票:-3回答:1

有一个返回指针的struct方法:

func (d *DataMap) Get(p Coord) *CellData {
    return &d.Data[p.X+(p.Y*d.Size)]
}

d.Data是一个CellData数组,它是一个包含多个字段的结构。使用这种方法,我可以修改每个字段的内部值,即:

example.Get(p).Something = 123

但我做不到这样的事情:

example.Get(p) = *yada (yada is a *CellData)

在哪里我想用另一个指针替换指针我得到:

cannot assign to example.Get(p)(undefined)

我究竟做错了什么?定义了函数的输出,不知道为什么我得到了这个错误。现在我通过直接访问数组来解决这个问题。

谢谢。

pointers go slice
1个回答
3
投票

Get返回一个指针,所以如果你想存储到指针指向的任何东西,你需要在开头添加一个*(指针取消引用):

*(example.Get(p)) = *yada
© www.soinside.com 2019 - 2024. All rights reserved.