-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
58 lines (48 loc) · 920 Bytes
/
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
package do
import (
"sync"
)
type Map[K comparable, T any] struct {
mu sync.Mutex
m map[K]T
}
func NewMap[K comparable, T any](size ...int) *Map[K, T] {
s := 0
if len(size) > 0 {
s = size[0]
}
return &Map[K, T]{
m: make(map[K]T, s),
}
}
func (m *Map[K, T]) Insert(key K, value T) {
m.mu.Lock()
m.m[key] = value
m.mu.Unlock()
}
func (m *Map[K, T]) Lookup(key K) (value T, ok bool) {
m.mu.Lock()
value, ok = m.m[key]
m.mu.Unlock()
return
}
func (m *Map[K, T]) Get(key K) (value T) {
value, _ = m.Lookup(key)
return
}
func (m *Map[K, T]) Range(f func(key K, value T)) {
m.mu.Lock()
defer m.mu.Unlock()
for k, v := range m.m {
f(k, v)
}
}
func (m *Map[K, T]) Remove(key K) {
m.mu.Lock()
delete(m.m, key)
m.mu.Unlock()
}
// ValueAs get value by key from *Map[K, any], and assert value type to T
func ValueAs[K comparable, T any](m *Map[K, any], key K) T {
return As[T](m.Get(key))
}