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