sequence

This article focuses on the HashSet of gost

HashSet

gost/container/set/hashset.go

var itemExists = struct{}{} type HashSet struct { Items map[interface{}]struct{} } func NewSet(values ... interface{}) *HashSet { set := &HashSet{Items: make(map[interface{}]struct{})} if len(values) > 0 { set.Add(values...) } return set } func (set *HashSet) Add(items ... interface{}) { for _, item := range items { set.Items[item] = itemExists } } func (set *HashSet) Remove(items ... interface{}) { for _, item := range items { delete(set.Items, item) } } func (set *HashSet) Contains(items ... interface{}) bool { for _, item := range items { if _, contains := set.Items[item]; ! contains { return false } } return true } func (set *HashSet) Empty() bool { return set.Size() == 0 } func (set *HashSet) Size() int { return len(set.Items) } func (set *HashSet) Clear() { set.Items = make(map[interface{}]struct{}) } func (set *HashSet) Values() []interface{} { values := make([]interface{}, set.Size()) count := 0 for item := range set.Items { values[count] = item count++ } return values } func (set *HashSet) String() string { str := "HashSet\n" var items []string for k := range set.Items { items = append(items, fmt.Sprintf("%v", k)) } str += strings.Join(items, ", ") return str }Copy the code

A HashSet defines the Items property; NewSet creates a HashSet based on values; It provides the Add, Remove, Contains, Empty, Size, Clear, Values, and String methods

The instance

gost/container/set/hashset_test.go

func TestSetNew(t *testing.T) { set := NewSet(2, 1) if actualValue := set.Size(); actualValue ! = 2 { t.Errorf("Got %v expected %v", actualValue, 2) } if actualValue := set.Contains(1); actualValue ! = true { t.Errorf("Got %v expected %v", actualValue, true) } if actualValue := set.Contains(2); actualValue ! = true { t.Errorf("Got %v expected %v", actualValue, true) } if actualValue := set.Contains(3); actualValue ! = false { t.Errorf("Got %v expected %v", actualValue, true) } }Copy the code

summary

The HashSet of gost defines the Items property, which is implemented through the map structure. It provides the Add, Remove, Contains, Empty, Size, Clear, Values, and String methods.

doc

  • gost