Receiving an instance of a struct from go lists


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.


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

Answered By – colm.anseo

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.