如何检查 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.
我需要一个函数:
func name (v interface{}) {
if is_slice() {
for _, i := range v {
my_var := i.(MyInterface)
... do smth
}
} else {
my_var := v.(MyInterface)
... do smth
}
}
如何在 Go 中执行 is_slice
?感谢任何帮助.
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
", x)
}
}
case
分支枚举了可能的类型,其中的 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.
测试它:
type MyInterface interface {
io.Writer
}
var i MyInterface = os.Stdout
name(i)
var s = []MyInterface{i, i}
name(s)
name("something else")
输出(在 Go Playground 上试试):
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
}
还有其他方法,使用包reflect
可以写一个更通用(也更慢)的解决方案,但如果你刚刚开始 Go,你不应该深入研究反射.
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屋!