简体   繁体   English

如何检查 interface{} 是否为切片

[英]How to check if interface{} is a slice

I'm noob in Go :) so my question may be stupid, but can't find answer, so.我是 Go 的菜鸟 :) 所以我的问题可能很愚蠢,但找不到答案,所以。

I need a function:我需要一个功能:

func name (v interface{}) {
    if is_slice() {
        for _, i := range v {
            my_var := i.(MyInterface)
            ... do smth
        }
    } else {
        my_var := v.(MyInterface)
        ... do smth
    }
}

How can I do is_slice in Go?我如何在 Go 中做is_slice Appreciate any help.感谢任何帮助。

In your case the type switch is the simplest and most convenient solution:在您的情况下,类型开关是最简单、最方便的解决方案:

func name(v interface{}) {
    switch x := v.(type) {
    case []MyInterface:
        fmt.Println("[]MyInterface, len:", len(x))
        for _, i := range x {
            fmt.Println(i)
        }
    case MyInterface:
        fmt.Println("MyInterface:", x)
    default:
        fmt.Printf("Unsupported type: %T\n", x)
    }
}

The case branches enumerate the possible types, and inside them the x variable will already be of that type, so you can use it so. case分支列举了可能的类型,在它们里面x变量已经是那种类型,所以你可以这样使用它。

Testing it:测试它:

type MyInterface interface {
    io.Writer
}

var i MyInterface = os.Stdout
name(i)
var s = []MyInterface{i, i}
name(s)
name("something else")

Output (try it on the Go Playground ):输出(在Go Playground上试试):

MyInterface: &{0x1040e110}
[]MyInterface, len: 2
&{0x1040e110}
&{0x1040e110}
Unsupported type: string

For a single type check you may also use type assertion :对于单个类型检查,您还可以使用类型断言

if x, ok := v.([]MyInterface); ok {
    // x is of type []MyInterface
    for _, i := range x {
        fmt.Println(i)
    }
} else {
    // x is not of type []MyInterface or it is nil
}

There are also other ways, using package reflect you can write a more general (and slower) solution, but if you're just starting Go, you shouldn't dig into reflection yet.还有其他方法,使用包reflect你可以编写一个更通用(和更慢)的解决方案,但如果你刚开始使用 Go,你不应该深入研究反射。

icza's answer is correct, but is not recommended by go creators : icza 的答案是正确的,但go 创作者不推荐:

interface{} says nothing interface{} 什么也没说

A better approach may be to define a function for each type you have:更好的方法可能是为您拥有的每种类型定义一个函数:

func name(v MyInterface) {
    // do something
}

func names(vs []MyInterface) {
    for _, v := range(vs) {
        name(v)
    }
}

The is_slice method can be something like this: is_slice方法可以是这样的:

func IsSlice(v interface{}) bool {
    return reflect.TypeOf(v).Kind() == reflect.Slice
}

Can also put additional condition of reflect.TypeOf(v).Kind() == reflect.Array if required.如果需要,还可以添加reflect.TypeOf(v).Kind() == reflect.Array附加条件。

From https://blog.golang.org/json来自https://blog.golang.org/json

Decoding arbitrary data解码任意数据

Consider this JSON data, stored in the variable b:考虑这个存储在变量 b 中的 JSON 数据:

b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)

Without knowing this data's structure, we can decode it into an interface{} value with Unmarshal:在不知道此数据结构的情况下,我们可以使用 Unmarshal 将其解码为 interface{} 值:

var f interface{} err := json.Unmarshal(b, &f) At this point the Go value in f would be a map whose keys are strings and whose values are themselves stored as empty interface values: var f interface{} err := json.Unmarshal(b, &f) 此时 f 中的 Go 值将是一个映射,其键是字符串,其值本身存储为空接口值:

f = map[string]interface{}{
    "Name": "Wednesday",
    "Age":  6,
    "Parents": []interface{}{
        "Gomez",
        "Morticia",
    },
}

To access this data we can use a type assertion to access f's underlying map[string]interface{}:要访问这些数据,我们可以使用类型断言来访问 f 的底层 map[string]interface{}:

m := f.(map[string]interface{})

We can then iterate through the map with a range statement and use a type switch to access its values as their concrete types:然后我们可以使用 range 语句遍历 map 并使用类型开关来访问它的值作为它们的具体类型:

for k, v := range m {
    switch vv := v.(type) {
    case string:
        fmt.Println(k, "is string", vv)
    case float64:
        fmt.Println(k, "is float64", vv)
    case []interface{}:
        fmt.Println(k, "is an array:")
        for i, u := range vv {
            fmt.Println(i, u)
        }
    default:
        fmt.Println(k, "is of a type I don't know how to handle")
    }
}

In this way you can work with unknown JSON data while still enjoying the benefits of type safety.通过这种方式,您可以处理未知的 JSON 数据,同时仍然享受类型安全的好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM