我厌倦了编写像[]int32->;[]int64这样的手动切片转换,因为在很多情况下,您需要将Slice与另一种类型一起使用. 因此,我try 为此编写一个泛型函数:
func convertSlice[T1 any, T2 any](t1 []T1) []T2 {
t2 := make([]T2, len(t1))
for i := range t1 {
t2[i] = T2(t1[i])
}
return t2
}
并想像使用它一样使用它
a := []int{1, 2, 3, 4, 5}
var b []int64 = convertSlice[int, int64](a)
但是我不能编译它,编译器说./prog.go:8:14: cannot convert t1[i] (variable of type T1 constrained by any) to type T2
那么,我怎么才能解决这个问题呢?
现场示例:https://go.dev/play/p/YYOLFjYt4mq
当然,我可以 for each 基本类型编写单独的函数,如下所示:
func convertNumericSlice[T1, T2 constraints.Integer | constraints.Float](t1 []T1) []T2 {}
func convertStringSlice[T1, T2 ~string](t1 []T1) []T2 {}
但这看起来一点也不像是很酷的通用化方式.