遍历接口数组 [英] Iterating over an array of interfaces

查看:48
本文介绍了遍历接口数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了代码:

switch v.(type) {
        case []interface{}:
            fmt.Println(reflect.TypeOf(v))
            for index, element := range v {
                fmt.Println("Inside for")
            }
        default:
            fmt.Println("I don't know how to handle this.")
        }

现在,我的 reflect.TypeOf(v)将类型输出为 [] interface {} .但是,我无法遍历接口数组.我遇到错误:不能在v范围内(类型接口{}).有人可以解释一下为什么吗?另外,有什么解决方法?

Now, my reflect.TypeOf(v) outputs the type as []interface {} . But, I'm not able to iterate over the array of interfaces. I encounter the error:cannot range over v (type interface {}). Could someone please explain me why ? Also, what's the workaround ?

推荐答案

类型切换,如果您希望访问转换为适当类型的变量,只需使用 switch x:= v.(type)之类的东西,在每种情况下, x 开关都会具有适当的价值.规范中有一个例子.您甚至可以执行 switch v:= v.(type),并且在switch语句中将存在v的阴影版本.

In a type switch, if you wish to access the variable casted to the appropriate type just use something like switch x := v.(type) and in each case of the switch x will be of the appropriate value. The spec has an example of this. You can even do switch v := v.(type) and within the switch statement there will be a shadowed version of v.

例如:

switch x := v.(type) {
case []interface{}:
        fmt.Printf("got %T\n", x)
        for i, e := range x {
                fmt.Println(i, e)
        }
default:
        fmt.Printf("I don't know how to handle %T\n", v)
}

游乐场

还要注意,您可以只使用%T"当您只想打印变量的类型时,使用 fmt.Printf 而不是(直接)使用反射包.

Also note that you can just use "%T" with fmt.Printf instead of (directly) using the reflect package when you just want to print the type of a variable.

最后,请注意,如果您有多个非默认子句,则需要使用类型开关,但是,例如在您的示例中,如果您确实只对一种类型感兴趣,则应该执行以下操作:

Finally, note that a type switch is what you want if you have multiple non-default clauses, but if, as in your example, you really only have one type you are interested in then instead you should do something like:

if x, ok := v.([]interface{}); ok {
        fmt.Printf("got %T\n", x)
        for i, e := range x {
                fmt.Println(i, e)
        }
} else {
        fmt.Printf("I don't know how to handle %T\n", v)
}

这篇关于遍历接口数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆