mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-18 00:22:41 +08:00
maps
This commit is contained in:
18
maps/map.go
18
maps/map.go
@ -6,7 +6,11 @@ import (
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
type Map[K constraints.Ordered, V any] interface {
|
||||
type hashable interface {
|
||||
constraints.Integer | constraints.Float | ~string
|
||||
}
|
||||
|
||||
type Map[K hashable, V any] interface {
|
||||
Set(key K, value V) // 设置值
|
||||
Get(key K) (value V, ok bool) // 获取值
|
||||
Exist(key K) bool // 键是否存在
|
||||
@ -14,19 +18,17 @@ type Map[K constraints.Ordered, V any] interface {
|
||||
Keys() []K // 获取所有键
|
||||
Values() []V // 获取所有值
|
||||
ToMap() map[K]V // 转换为map
|
||||
Clone() Map[K, V] // 复制
|
||||
Clear() // 清空
|
||||
Count() int // 数量
|
||||
Iter() <-chan *Entry[K, V] // 迭代器
|
||||
ForEach(f func(K, V) bool) // ForEach
|
||||
// Iter() <-chan *Entry[K, V] // 迭代器
|
||||
ForEach(f func(K, V) bool) // ForEach
|
||||
}
|
||||
|
||||
type Entry[K constraints.Ordered, V any] struct {
|
||||
type Entry[K hashable, V any] struct {
|
||||
Key K
|
||||
Value V
|
||||
}
|
||||
|
||||
func Merge[K comparable, V any](mm ...map[K]V) map[K]V {
|
||||
func Merge[K hashable, V any](mm ...map[K]V) map[K]V {
|
||||
ret := make(map[K]V)
|
||||
for _, m := range mm {
|
||||
for k, v := range m {
|
||||
@ -38,7 +40,7 @@ func Merge[K comparable, V any](mm ...map[K]V) map[K]V {
|
||||
}
|
||||
|
||||
// 按照键值生成字符串
|
||||
func Join[K constraints.Ordered, V any](m Map[K, V], sep string, f func(k K, v V) string) string {
|
||||
func Join[K hashable, V any](m Map[K, V], sep string, f func(k K, v V) string) string {
|
||||
slice := make([]string, 0, m.Count())
|
||||
|
||||
m.ForEach(func(k K, v V) bool {
|
||||
|
Reference in New Issue
Block a user