Tough Guy
Tough Guy

Reputation: 19

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.

Upvotes: 1

Views: 45

Answers (1)

colm.anseo
colm.anseo

Reputation: 22017

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

Upvotes: 3

Related Questions