普通网友 2014-05-10 13:53
浏览 1417
已采纳

无法从[[] interface {}`断言类型[[] string`

I am trying to process some data retrieved from mongodb (mgo).

Unfortunately I am unable to assert the correct type for a list of strings. The function I am working on is the following:

func generate_version_histogram(userStats []interface{}) map[string]int {
    var histogram map[string]int
    for _, _u := range userStats {
        u := _u.(bson.M)
        for _, version := range (u["v"]).([]string) {
            if _, alreadyhere := histogram[version]; alreadyhere {
                histogram[version] += 1
            } else {
                histogram[version] = 1
            }
        }
    }
    return histogram
}

Unfortunately I am getting this following run-time panic:

interface conversion: interface is []interface {}, not []string

Any idea on why this is happening? How can I retrieve those strings?

  • 写回答

2条回答 默认 最新

  • dongyan7950 2014-05-10 14:14
    关注

    This is a common mistake with Go.

    The reason is as follows: in Go []interface{} is not an interface, it's a slice type, whose elements are each the interface{} type.

    Because each element is a interface{}, rather than, say, an int or Foo, more memory is taken up by each element (interface{} needs to store the underlying type, and the value contained). Therefore, it's not possible to directly convert a []interface value into a []string or []T value.

    How do you convert []interface{} into []string, then?

    The solution is quite simple — you convert each element.

    package main
    
    import "fmt"
    
    func main() {
        foo := []interface{}{"a", "b", "c"}
    
        // we want to convert foo to a []string
        out := []string{}
    
        for _, v := range foo {
            // using a type assertion, convert v to a string
            out = append(out, v.(string))
        }
    
        fmt.Println(out)
    }
    

    Runnable example here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)