代码拉取完成,页面将自动刷新
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。