如何检查interface {}是否是切片 [英] How to check if interface{} is a slice

查看:186
本文介绍了如何检查interface {}是否是切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是go的noob)所以我的问题可能是愚蠢的,但无法找到答案,所以。



我需要一个函数:

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

我该怎么做 is_slice 在Go?感谢任何帮助。

type switch 是最简单和最方便的解决方案:

  func name v接口{}){
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 )
默认值:
fmt.Printf(不支持的类型:%T \ n,x)
}
}

case 分支列举了可能的类型,其中 x 变量已经是该类型的,所以你可以使用它。



测试它:

 类型MyInterface接口{
io.Writer
}

var i MyInterface = os.Stdout
nam e(i)
var s = [] MyInterface {i,i}
名称
名称(别的东西)

输出(在 Go Playground ):

  MyInterface:& {0x1040e110} 
[] MyInterface,len:2
& {0x1040e110}
& {0x1040e110}
不支持的类型:字符串

对于单一类型的检查,您也可以使用键入断言

  if x,ok:= v。([] MyInterface); OK {
// x是[]的类型[] MyInterface
for _,i:=范围x {
fmt.Println(i)
}
} else {
// x不是类型[] MyInterface或它是零
}

还有其他一些方法,使用包 反映 你可以写一个更一般的(更慢的)解决方案,但是如果你刚开始使用Go,你就不应该深入思考。

I'm noob in Go :) so my question may be stupid, but can't find answer, so.

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? 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.

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):

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.

这篇关于如何检查interface {}是否是切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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