当我编译我的代码时,我收到以下错误消息,不知道为什么会发生.有人可以帮我指出原因吗?先感谢您.
不能在赋值时使用px.InitializePaxosInstance(val)(类型PaxosInstance)作为类型*PaxosInstance
type Paxos struct {
instance map[int]*PaxosInstance
}
type PaxosInstance struct {
value interface{}
decided bool
}
func (px *Paxos) InitializePaxosInstance(val interface{}) PaxosInstance {
return PaxosInstance {decided:false, value: val}
}
func (px *Paxos) PartAProcess(seq int, val interface{}) error {
px.instance[seq] = px.InitializePaxosInstance(val)
return nil
Run Code Online (Sandbox Code Playgroud)
}
Ray*_*ear 15
你的地图期望一个指向a PaxosInstance(*PaxosInstance)的指针,但是你正在向它传递一个struct值.更改Initialize函数以返回指针.
func (px *Paxos) InitializePaxosInstance(val interface{}) *PaxosInstance {
return &PaxosInstance {decided:false, value: val}
}
Run Code Online (Sandbox Code Playgroud)
现在它返回一个指针.您可以使用&和(如果需要)再次取消引用变量的指针*.经过一条线之后
x := &PaxosInstance{}
Run Code Online (Sandbox Code Playgroud)
要么
p := PaxosInstance{}
x := &p
Run Code Online (Sandbox Code Playgroud)
值类型x现在是*PaxosInstance.如果您需要(无论出于何种原因),您可以将其取消引用(按照指向实际值的指针)返回到PaxosInstance结构值中
p = *x
Run Code Online (Sandbox Code Playgroud)
您通常不希望将结构作为实际值传递,因为Go是按值传递,这意味着它将复制整个事物.
至于读取编译器错误,您可以看到它告诉您的内容.类型PaxosInstance和类型*PaxosInstance不一样.
结构中的instance字段Paxos是整数键 到结构指针的映射PaxosInstance。
你打电话的时候:
px.instance[seq] = px.InitializePaxosInstance(val)
Run Code Online (Sandbox Code Playgroud)
您正在尝试将具体的(而非指针)PaxosInstance结构分配给的元素(px.instance即指针)。
您可以通过返回PaxosInstancein 的指针来减轻这种情况InitializePaxosInstance,如下所示:
func (px *Paxos) InitializePaxosInstance(val interface{}) *PaxosInstance {
return &PaxosInstance{decided: false, value: val}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以instance将Paxos结构中的字段修改为不是指针映射:
type Paxos struct {
instance map[int]PaxosInstance
}
Run Code Online (Sandbox Code Playgroud)
您选择哪个选项取决于您的用例。
| 归档时间: |
|
| 查看次数: |
15581 次 |
| 最近记录: |