包含
Contains操作其实就是查询操作,看看有没有对应的Item存在,可以利用Map的特性来实现,但是由于不需要Value的数值,所以可以用 _,ok来达到目的:
func (s *Set) Contains(item interface{}) bool {
_, ok := s.m[item]
return ok
}
长度和清除
获取Set长度很简单,只需要获取底层实现的Map的长度即可:
func (s *Set) Size() int {
return len(s.m)
}
清除操作的话,可以通过重新初始化Set来实现,如下即为实现过程:
func (s *Set) Clear() {
s.m = make(map[interface{}]struct{})
}
相等
判断两个Set是否相等,可以通过循环遍历来实现,即将A中的每一个元素,查询在B中是否存在,只要有一个不存在,A和B就不相等,实现方式如下所示:
func (s *Set) Equal(other *Set) bool {
// 如果两者Size不相等,就不用比较了
if s.Size() != other.Size() {
return false
}
// 迭代查询遍历
for key := range s.m {
// 只要有一个不存在就返回false
if !other.Contains(key) {
return false
}
}
return true
}
子集
判断A是不是B的子集,也是循环遍历的过程,具体分析在上面已经讲述过,实现方式如下所示:
func (s *Set) IsSubset(other *Set) bool {
// s的size长于other,不用说了
if s.Size() > other.Size() {
return false
}
// 迭代遍历
for key := range s.m {
if !other.Contains(key) {
return false
}
}
return true
}
Ok,以上就是Go中Set的主要函数实现方式,还是很有意思的。继续加油。也希望大家多多支持易采站长站。









