您可以像平常一样将值转换为参数类型。
从提案来看类型转换 https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md#type-conversions:
在具有两个类型参数的函数中From
and To
,类型的值From
可以转换为类型的值To
if From约束的类型集中的所有类型都可以转换为To约束的类型集中的所有类型。
在这种情况下,你实际上没有From
因为它是切片索引int
;目的地类型将是T
(即使这可能不是您想要的,请参阅下面的原因)。当然int
可以转换为T
的类型集,因为它仅包含数字类型(尽管截断或精度损失 https://go.dev/ref/spec#Conversions的情况下int8
or float64
!)
indexs = append(indexs, T(i))
但是你的程序将索引切片声明为[]T
,这意味着将通用函数实例化为:
is := FindIndexValue([]float64{1,5,7,9}, float64(9))
将产生类型的结果[]float64
。由于返回值是切片索引,因此始终是int
,这没有多大意义。
更好的是简单地返回[]int
:
func FindIndexValue[T Number](array []T, value T) []int {
var indices []int
for i := range array {
// match on the generically typed slice item
if array[i] == value {
// store slice indices as ints
indices = append(indexs, i)
}
}
return indices
}
操场:https://gotipplay.golang.org/p/EykXppG2qJa https://gotipplay.golang.org/p/EykXppG2qJa