从Go列表中接收一个结构体实例。

huangapple go评论73阅读模式
英文:

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 前面加上点号时,它无法识别为正确的类型,我无法访问 RndSlotVal 作为 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

huangapple
  • 本文由 发表于 2022年4月9日 00:31:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/71800440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定