-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathset.go
53 lines (50 loc) · 857 Bytes
/
set.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
package gotype
//用于演示Golang相关算法所写的数据结构
import (
"sync"
)
type Set struct {
m map[interface{}]bool
sync.RWMutex
}
func NewSet() *Set {
return &Set{
m: map[interface{}]bool{},
}
}
func (s *Set) Add(item interface{}) {
s.Lock()
defer s.Unlock()
s.m[item] = true
}
func (s *Set) Remove(item interface{}) {
s.Lock()
defer s.Unlock()
delete(s.m, item)
}
func (s *Set) Contains(item interface{}) bool {
s.RLock()
defer s.RUnlock()
_, ok := s.m[item]
return ok
}
func (s *Set) Len() int {
return len(s.List())
}
func (s *Set) Clear() {
s.RLock()
defer s.Unlock()
s.m = map[interface{}]bool{}
}
func (s *Set) IsEmpty() bool {
return s.Len() == 0
}
func (s *Set) List() []interface{} {
s.RLock()
defer s.RUnlock()
list := []interface{}{}
for item := range s.m {
list = append(list, item)
}
return list
}