Cannot use as type in assignment in go

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

when I compile my code, I get the following error message, not sure why it happens. Can someone help me point why? Thank you in advance.

cannot use px.InitializePaxosInstance(val) (type PaxosInstance) as type *PaxosInstance in assignment

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  

}

回答1:

Your map is expecting a pointer to a PaxosInstance (*PaxosInstance), but you are passing a struct value to it. Change your Initialize function to return a pointer.

func (px *Paxos) InitializePaxosInstance(val interface{}) *PaxosInstance {     return &PaxosInstance {decided:false, value: val} } 

Now it returns a pointer. You can take the pointer of a variable using & and (should you ever need to) dereference it again with *. After a line like

x := &PaxosInstance{}  

or

p := PaxosInstance{} x := &p 

the value type of x is now *PaxosInstance. And if you ever need to (for whatever reason), you can dereference it (follow the pointer to the actual value) back into a PaxosInstance struct value with

p = *x 

You usually do not want to pass structs around as actual values, because Go is pass-by-value, which means it will copy the whole thing.

As for reading the compiler errors, you can see what it was telling you. The type PaxosInstance and type *PaxosInstance are not the same.



回答2:

The instance field within the Paxos struct is a map of integer keys to pointers to PaxosInstance structs.

When you call:

px.instance[seq] = px.InitializePaxosInstance(val) 

You're attempting to assign a concrete (not pointer) PaxosInstance struct into an element of px.instance, which are pointers.

You can alleviate this by returning a pointer to a PaxosInstance in InitializePaxosInstance, like so:

func (px *Paxos) InitializePaxosInstance(val interface{}) *PaxosInstance {     return &PaxosInstance{decided: false, value: val} } 

or you could modify the instance field within the Paxos struct to not be a map of pointers:

type Paxos struct {     instance   map[int]PaxosInstance } 

Which option you choose is up to your use case.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!