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

无法从[[] 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条)

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常