Files
bl/common/utils/syncmap.go

43 lines
809 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils
import (
"sync"
)
// 定义一个泛型的 SyncMap支持任意类型的键和值
type SyncMap[K comparable, V any] struct {
m sync.Map
}
// 设置键值对
func (sm *SyncMap[K, V]) Store(key K, value V) {
sm.m.Store(key, value)
}
func (sm *SyncMap[K, V]) LoadOrStore(key K, value V) (V, bool) {
val, ok := sm.m.LoadOrStore(key, value)
return val.(V), ok
}
// 获取键对应的值
func (sm *SyncMap[K, V]) Load(key K) (V, bool) {
val, ok := sm.m.Load(key)
if ok {
return val.(V), true
}
var zeroValue V
return zeroValue, false
}
// 删除键值对
func (sm *SyncMap[K, V]) Delete(key K) {
sm.m.Delete(key)
}
// 遍历所有键值对
func (sm *SyncMap[K, V]) Range(f func(key K, value V) bool) {
sm.m.Range(func(key, value any) bool {
return f(key.(K), value.(V))
})
}