doulu1945 2017-07-06 16:19
浏览 260

golang:访问接口切片中的值

I have a data structure which comes of out go-spew looking like this:

([]interface {}) (len=1 cap=1) {
 (string) (len=1938) "value"
}

It is of type []interface {}

How can I print this value with fmt, or access it in some way so that I can use it.

  • 写回答

1条回答 默认 最新

  • douke1942 2017-07-06 16:41
    关注

    You can use type assertions or reflection work with the generic interface{} to an underlying type. How you do this depends on your particular use case. If you can expect the interface{} to be a []interface{} as in your example, you can:

    if sl, ok := thing.([]interface{}); ok {
        for _, val := range sl {
            fmt.Println(val)
            // Or if needed, coerce val to its underlying type, e.g. strVal := val.(string)
        }
    }
    

    (Playground link)

    If you can't make assumptions about the underlying type, you'll need to do some black magic using reflect.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用