在某些情况下一个函数可能既需要接收[]string类型的切片也可能接收[]int类型的切片,或接收自定义类型的切片。我首先想到的办法是创建一个[]interface{}类型的切片,如下所示:
func demo(s []interface{}) {
for _, ele := range s {
fmt.Println(ele)
}
}
func Test(t *testing.T) {
s := []int{1, 2, 3}
demo(s)
}
但不幸的是,我得到了“cannot use s (type []int) as type []interface {} in argument to demo”这个错误。原因是interface{}类型的变量可以指向任意类型的值,但[]interface{}类型的指针只能指向[]interface{}类型的值而不能指向任意类型的切片。
为了实现上述功能,我想到的办法是利用反射中的Slice:
func demo(s interface{}) {
sv := reflect.ValueOf(s)
svs := sv.Slice(0, sv.Len())
for i := 0; i < svs.Len(); i++ {
e := svs.Index(i).Interface()
switch e.(type) {
case string:
fmt.Println("string", e)
case int:
fmt.Println("int", e)
}
}
}
func Test(t *testing.T) {
s1 := []int{1, 2, 3}
demo(s1)
s2 := []string{"a", "b", "c"}
demo(s2)
}

本文探讨了在Go语言中如何使用反射技术处理不同类型的切片,包括int和string等,通过示例代码展示了如何将任意类型的切片转换为interface{}

被折叠的 条评论
为什么被折叠?



