1 Star 0 Fork 0

NodeMessage/gotools

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
map.go 1.13 KB
一键复制 编辑 原始数据 按行查看 历史
王居三木 提交于 2024-06-22 15:01 +08:00 . move date,list,map pkg to lang
package lang
import (
"errors"
"sync"
)
type KeyValue[K comparable, V any] struct {
Key K
Value V
}
type Map[K comparable, V any] struct {
pairs map[K]V
lock sync.RWMutex
}
func MapNew[K comparable, V any]() *Map[K, V] {
return &Map[K, V]{}
}
func (m *Map[K, V]) equals(key1, key2 K) bool {
return key1 == key2
}
func (m *Map[K, V]) Put(key K, value V) {
m.lock.Lock()
defer m.lock.Unlock()
m.pairs[key] = value
}
func (m *Map[K, V]) Get(key K) (V, error) {
m.lock.RLock()
defer m.lock.RUnlock()
var zeroValue V
value, exists := m.pairs[key]
if !exists {
return zeroValue, errors.New("key not found")
}
return value, nil
}
func (m *Map[K, V]) Remove(key K) {
m.lock.Lock()
defer m.lock.Unlock()
delete(m.pairs, key)
}
func (m *Map[K, V]) Keys() []K {
m.lock.RLock()
defer m.lock.RUnlock()
keys := make([]K, 0, len(m.pairs))
for key := range m.pairs {
keys = append(keys, key)
}
return keys
}
func (m *Map[K, V]) ContainKey(key K) bool {
m.lock.RLock()
defer m.lock.RUnlock()
_, exists := m.pairs[key]
return exists
}
func (m *Map[K, V]) Clear() {
m.lock.Lock()
defer m.lock.Unlock()
m.pairs = make(map[K]V)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/node-message/gotools.git
git@gitee.com:node-message/gotools.git
node-message
gotools
gotools
v0.0.1

搜索帮助