问题描述
当我编译我的代码时,我收到以下错误消息,不知道为什么会发生。有人可以帮我指出原因吗?
$ b
类型Paxos struct {
实例映射[int] * PaxosInstance
}
类型PaxosInstance结构{
接口{}
决定bool
}
func(px * Paxos)InitializePaxosInstance(val接口{}} PaxosInstance {
返回PaxosInstance {决定:false,value:val}
}
func(px * Paxos)PartAProcess(seq int,val interface {})error {
px.instance [seq] = px.InitializePaxosInstance(val)
return nil
}
您的地图期待指向 PaxosInstance
( * PaxosInstance
),但是你传递一个struct值给它。改变你的Initialize函数返回一个指针。
pre $ func(px * Paxos)InitializePaxosInstance(val interface {})* PaxosInstance { b $ b return& PaxosInstance {决定:false,value:val}
}
现在它返回一个指针。你可以使用&
和(需要的话)再次用 *
取消引用变量的指针, 。在诸如
x:=& PaxosInstance {}
或
p:= PaxosInstance {}
x :=& p
x 现在是
* PaxosInstance
。如果您需要(无论出于何种原因),您可以使用
$将其取消引用(使用指向实际值的指针)回到 PaxosInstance
struct值b
$ b p = * x
你通常不想将结构作为实际值传递,因为Go是按值传递的,这意味着它将复制整个事物。
至于阅读编译器错误,你可以看到它告诉你什么。类型 PaxosInstance
和类型 * PaxosInstance
不一样。
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.
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
}
解决方案 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.
这篇关于在go中不能用作赋值中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!