【问题标题】:How to retrieve struct pointer from Go list如何从 Go 列表中检索结构指针
【发布时间】:2021-01-14 14:44:40
【问题描述】:

我有一个结构

type clientData struct {
    msg    Message
    connId int
}

我正在尝试将其添加到 Go List

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

现在,我如何从 List 中以 *clientData 数据类型取回数据?我尝试了l.Front().Value,但它返回了一个接口......我很确定我不明白 Go here 的编组/编组逻辑......

【问题讨论】:

    标签: go pointers linked-list


    【解决方案1】:

    go 中的集合包含 raw typesElement.Value ?? 为空 interface{})。每次从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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多