
我正在尝试使用泛型构建一个函数,它将接口切片转换为 t 类型的切片。
我想出了以下内容:
func convertInterfaceArray[T any](input []any, res []T) {
for _, item := range input {
res = append(res, item.(reflect.TypeOf(res[0])))
}
}
但是,这不会编译。但你明白了。 t 可以是任何类型,我有一个 []any 类型的输入切片需要转换为 []t
正确答案
断言键入 t 的值。不需要反射。
for _, item := range input {
res = append(res, item.(T))
}










