聊聊gost的HashSet

/ golang / 没有评论 / 10浏览

本文主要研究一下gost的HashSet

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
}

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方法。

doc