-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.go
60 lines (47 loc) · 1.03 KB
/
map.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package types
import (
"sync"
)
// Map represents a thread-safe ordered map.
type Map[K comparable, V any] struct {
sync.RWMutex
items map[K]V
}
// NewMap creates a new instance of Map.
func NewMap[K comparable, V any]() *Map[K, V] {
return &Map[K, V]{
items: make(map[K]V),
}
}
// Put inserts a key-value pair into the map.
func (om *Map[K, V]) Put(key K, value V) {
om.Lock()
defer om.Unlock()
om.items[key] = value
}
// Get retrieves the value associated with the given key.
func (om *Map[K, V]) Get(key K) (V, bool) {
om.RLock()
defer om.RUnlock()
value, exists := om.items[key]
return value, exists
}
// Remove deletes a key-value pair from the map.
func (om *Map[K, V]) Remove(key K) {
om.Lock()
defer om.Unlock()
delete(om.items, key)
}
func (om *Map[K, V]) Length() int {
om.RLock()
defer om.RUnlock()
return len(om.items)
}
// Iterate executes a function for each key, value pair
func (om *Map[K, V]) Iterate(exec func(K, V)) {
om.RLock()
defer om.RUnlock()
for key, val := range om.items {
exec(key, val)
}
}