Cannot use destination as type in go

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

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

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 

}

+5
source share
2 answers

Your map expects a pointer to PaxosInstance ( *PaxosInstance ), but you pass it a struct value. Modify the 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 variable pointer with & and (if you ever need to) find it again with * . After a line like

 x := &PaxosInstance{} 

or

 p := PaxosInstance{} x := &p 

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

 p = *x 

Usually you do not want to pass structures as actual values, because Go is a pass by value, which means that it will copy all of this.

Regarding reading compiler errors, you can see what it told you. The type of PaxosInstance and type *PaxosInstance do not match.

+9
source

The instance field in the Paxos structure is a map of integer keys for pointers to PaxosInstance structs.

When you call:

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

You are trying to assign a specific (not a pointer) PaxosInstance struct to the px.instance element, which is a pointer.

You can facilitate this by returning the pointer to PaxosInstance in InitializePaxosInstance , for example:

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

or you can change the instance field in the Paxos structure Paxos that there is no map pointer:

 type Paxos struct { instance map[int]PaxosInstance } 

Which option you choose depends on your use case.

+4
source

All Articles