[已解决] go 泛型范围可以简化复用吗?有人知道这个地方可以有什么简化的写法吗
关于 go 泛型范围可以简化复用吗。因为 map 的 key 必须是可比较类型的。这个地方要把所有可比较的类型都这样写一遍吗,有没有可以复用的写法。如果我有很多地方都需要 map k 的泛型,要在每个里面都用|
重新写一遍吗。
func Map2Splice[T any, K int | string | int64 | int32](mapData map[K]T) []T {
listData := make([]T, len(mapData))
for _, t := range mapData {
listData = append(listData, t)
}
return listData
}
可以这样写
type OrderedType interface {
Integer | Float | ~string
}
type Integer interface {
Signed | Unsigned
}
type Signed interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type Unsigned interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
type Float interface {
~float32 | ~float64
}
func Map2Splice[T any, K OrderedType](mapData map[K]T) []T {
listData := make([]T, len(mapData))
for _, t := range mapData {
listData = append(listData, t)
}
return listData
}
不是很懂你问的,这个是你想要的吗?
泛型作者写的 map