首先,我们需要通过测试来确保我们正在处理切片:
reflect.TypeOf(<var>).Kind() == reflect.Slice
如果没有该检查,您将面临运行时恐慌的风险。因此,既然我们知道我们正在处理切片,则查找元素类型非常简单:
typ :=reflect.TypeOf(<var>).Elem()
由于我们可能期望许多不同的元素类型,因此可以使用switch语句来区分:
t := reflect.TypeOf(<var>)if t.Kind() != reflect.Slice { // handle non-slice vars}switch t.Elem().Kind() { // type of the slice element case reflect.Int: // Handle int case case reflect.String: // Handle string case ... default: // custom types or structs must be explicitly typed // using calls to reflect.TypeOf on the defined type.}


