45 lines
1.2 KiB
Go
45 lines
1.2 KiB
Go
package utils
|
|
|
|
// ToMap converts a slice to a map with the keyFunc determining what the key of a value should be.
|
|
// Will override any double values.
|
|
func ToMap[T any, K comparable](slice []T, keyFunc func(T) K) map[K]T {
|
|
m := make(map[K]T, len(slice))
|
|
for _, v := range slice {
|
|
m[keyFunc(v)] = v
|
|
}
|
|
return m
|
|
}
|
|
|
|
// ToSliceMap converts a slice to a map with the keyFunc determining what the key of a value should be.
|
|
// Will append to the slice if the key already exists.
|
|
func ToSliceMap[T any, K comparable](slice []T, keyFunc func(T) K) map[K][]T {
|
|
m := make(map[K][]T, len(slice))
|
|
for _, v := range slice {
|
|
key := keyFunc(v)
|
|
m[key] = append(m[key], v)
|
|
}
|
|
return m
|
|
}
|
|
|
|
// 定义泛型约束:只允许数值类型(整数、浮点数等)
|
|
type Number interface {
|
|
int | int8 | int16 | int32 | int64 |
|
|
uint | uint8 | uint16 | uint32 | uint64 |
|
|
float32 | float64
|
|
}
|
|
|
|
// Max 泛型函数:接收两个同类型的 Number 参数,返回最大值
|
|
func Max[T Number](a, b T) T {
|
|
if a > b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
// Max 泛型函数:接收两个同类型的 Number 参数,返回最大值
|
|
func Min[T Number](a, b T) T {
|
|
if a < b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|