假设您有一个接受 t interface{}
的函数。如果确定 t
是一个切片,我如何 range
覆盖该切片?
func main() {
data := []string{"one","two","three"}
test(data)
moredata := []int{1,2,3}
test(data)
}
func test(t interface{}) {
switch reflect.TypeOf(t).Kind() {
case reflect.Slice:
// how do I iterate here?
for _,value := range t {
fmt.Println(value)
}
}
}
Go 游乐场示例: http ://play.golang.org/p/DNldAlNShB
原文由 Nucleon 发布,翻译遵循 CC BY-SA 4.0 许可协议
Well I used
reflect.ValueOf
and then if it is a slice you can callLen()
andIndex()
on the value to get thelen
of the索引处的切片和元素。我认为您无法使用范围操作来执行此操作。Go 游乐场示例: http ://play.golang.org/p/gQhCTiwPAq