64 lines
875 B
Go
64 lines
875 B
Go
package set
|
|
|
|
import (
|
|
"strings"
|
|
)
|
|
|
|
// 业务场景可能有些需要便利查找的部分可以替换为 Set
|
|
|
|
var Empty = struct{}{}
|
|
|
|
type Set map[string]struct{}
|
|
|
|
func NewSet(size int) Set {
|
|
if size == 0 {
|
|
return make(Set)
|
|
}
|
|
return make(Set, size)
|
|
}
|
|
|
|
func NewSetBySlice(keys []string) Set {
|
|
s := NewSet(len(keys))
|
|
s.SetSlice(keys)
|
|
return s
|
|
}
|
|
|
|
func (s Set) Has(key string) (has bool) {
|
|
_, has = s[key]
|
|
return
|
|
}
|
|
|
|
func (s Set) Set(key string) Set {
|
|
s[key] = Empty
|
|
return s
|
|
}
|
|
|
|
func (s Set) SetSlice(keys []string) Set {
|
|
for _, key := range keys {
|
|
s[key] = Empty
|
|
}
|
|
return s
|
|
}
|
|
|
|
func (s Set) Del(key string) {
|
|
delete(s, key)
|
|
}
|
|
|
|
func (s Set) String() string {
|
|
var (
|
|
str strings.Builder
|
|
idx int
|
|
)
|
|
str.WriteByte('[')
|
|
for key := range s {
|
|
if idx > 0 {
|
|
str.WriteByte(',')
|
|
}
|
|
str.WriteString(key)
|
|
idx++
|
|
}
|
|
str.WriteByte(']')
|
|
|
|
return str.String()
|
|
}
|