英文:
Receiving an instance of a struct from go lists
问题
我在Go语言中有一个结构体,如下所示:
type AcceptMsg struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Rnd *Round `protobuf:"bytes,1,opt,name=rnd,proto3" json:"rnd,omitempty"`
Slot *Slot `protobuf:"bytes,2,opt,name=slot,proto3" json:"slot,omitempty"`
Val *Value `protobuf:"bytes,3,opt,name=val,proto3" json:"val,omitempty"`
}
我将该结构体的实例添加到了一个 acceptMsgQueue *list.List
中。我的问题是,当我从列表中接收到这些实例时,如何访问实例的变量:
for f := p.acceptMsgQueue.Front(); f != nil; f = f.Next() {
acceptMsg := f.Value
}
当我在VSCode中在 acceptMsg
前面加上点号时,它无法识别为正确的类型,我无法访问 Rnd
、Slot
和 Val
作为 acceptMsg
的属性。
英文:
I have a struct in go which is:
type AcceptMsg struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Rnd *Round `protobuf:"bytes,1,opt,name=rnd,proto3" json:"rnd,omitempty"`
Slot *Slot `protobuf:"bytes,2,opt,name=slot,proto3" json:"slot,omitempty"`
Val *Value `protobuf:"bytes,3,opt,name=val,proto3" json:"val,omitempty"`
}
I have added instances from that struct into a acceptMsgQueue *list.List
my question is, how can I access the variables of the instance when I receive them from the list:
for f := p.acceptMsgQueue.Front(); f != nil; f = f.Next() {
acceptMsg := f.Value
}
when I put the dot in from of acceptMsg
in vscode it doesn't recognize it as the correct type and I do not have access to Rnd
and Slot
and Val
as the properties of acceptMsg
.
答案1
得分: 3
从文档中可以看到,列表的元素值使用any
(也称为interface{}
)存储:
type Element struct {
Value any
}
因此,要查看原始的具体类型值,你需要执行一个type assertion:
acceptMsg, ok := f.Value.(AcceptMsg) // 如果动态类型正确,ok==true
英文:
From the docs a list's element value is store using any
(a.k.a. interface{}
):
type Element struct {
Value any
}
so to see your original concrete-typed value, you need to perform a type assertion:
acceptMsg, ok := f.Value.(AcceptMsg) // ok==true if dynamic type is correct
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论