简体   繁体   中英

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...

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM