序
本文主要研究一下gost的HashSet
HashSetgost/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}
HashSet定義了Items屬性;NewSet根據values來建立HashSet;它提供了Add、Remove、Contains、Empty、Size、Clear、Values、String方法
例項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) }}
小結gost的HashSet定義了Items屬性,它透過map結構來實現,它提供了Add、Remove、Contains、Empty、Size、Clear、Values、String方法。
docgost
最新評論