gabbar0x
gabbar0x

Reputation: 4246

How to retrieve struct pointer from Go list

I have a struct

type clientData struct {
    msg    Message
    connId int
}

I'm trying to add this to a Go List as such

l := list.New()
l.PushBack(&clientData {
    msg: Message {
       some fields  
    },
    connId: 1
});

Now, how do I get back the data as a *clientData data type back from the List ? I tried l.Front().Value but that returns an interface... I'm pretty sure I don't understand the marshalling/marshalling logic for Go here...

Upvotes: 0

Views: 46

Answers (1)

kozmo
kozmo

Reputation: 4471

Collection in go contains a raw types (Element.Value 👉🏻 empty interface{}). You have to assign the type every time, when get value from the list:

l := list.New()
l.PushBack(&clientData {
    msg: Message {
       some fields  
    },
    connId: 1,
})

cd, ok := l.Front().Value.(*clientData)
if !ok {
    panic(errors.New("not a client type"))
}
fmt.Println(cd.connId)

Upvotes: 1

Related Questions