生成了以下代码(因此不能将其更改为type Enum interface { int32 }):
type Enum int32对于int32,有许多这样的类型定义。
我正在尝试创建一个泛型函数,该函数可以将这类类型定义的一部分转换为[]int32
func ConvertToInt32Slice[T int32](ts []T) []int32 {
return lo.Map(ts, func(t T, _ int) int32 {
return int32(t)
})
}但是以下是Type does not implement constraint 'interface{ int32 }' because type is not included in type set ('int32')的抱怨
type Int32 int32
var int32s []Int32
i32s := ConvertToInt32Slice(int32s)实现泛型函数所需的是什么,以便按预期的方式使用?
发布于 2022-11-26 04:15:28
看起来,您需要一个对具有基础类型int32的所有类型进行操作的泛型函数。这就是倾斜(~)令牌的意义所在。应该将函数的签名更改为:
func ConvertToInt32Slice[T ~int32](ts []T) []int32另见:What's the meaning of the new tilde token ~ in Go?
constraints.Integer也可以工作,因为它被定义为:
type Integer interface {
Signed | Unsigned
}https://pkg.go.dev/golang.org/x/exp/constraints#Integer
其定义为:
type Signed interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type Unsigned interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}因此,这给出了将任何整数类型作为基础类型的所有类型。
如果您只对以int32作为其基础类型的类型感兴趣,则应该使用~int32。
https://stackoverflow.com/questions/74579223
复制相似问题