在某些情况下一个函数可能既需要接收[]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)
}