企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> # 自制并发安全字典 ```go package main import ( "sync" "fmt" ) // 一个自制的简易并发安全字典 type CustomMap struct { m map[interface{}]interface{} mu sync.RWMutex } //TODO : 初始化 func NewCustomMap() *CustomMap { return &CustomMap{ m: make(map[interface{}]interface{}), } } //TODO: 根据键获取值 func (cm *CustomMap) Load(key interface{}) (value interface{}, ok bool) { cm.mu.Lock() value, ok = cm.m[key] cm.mu.Unlock() return } //TODO : 添加键值 func (cm *CustomMap) Store(key, value interface{}) { cm.mu.Lock() cm.m[key] = value cm.mu.Unlock() } //TODO : 修改键值 func (cm *CustomMap) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) { cm.mu.Lock() actual, loaded = cm.m[key] if !loaded { return } cm.m[key] = value cm.mu.Unlock() return value, true } //TODO : 删除键值 func (cm *CustomMap) Delete(key interface{}) { cm.mu.Lock() delete(cm.m, key) cm.mu.Unlock() } //TODO : 遍历键值 func (cm *CustomMap) Range(f func(key, value interface{}) bool) { cm.mu.RLock() for k, v := range cm.m { f(k, v) } cm.mu.RUnlock() } func main() { cm := NewCustomMap() s := []struct { k int v string }{ {1, "a"}, {2, "b"}, {3, "c"}, } //添加键值 for k, v := range s { cm.Store(k, v) } //遍历 cm.Range(func(k, v interface{}) bool { fmt.Println(k, v) return true }) } ```