Go的Set实现

Go的Set实现

  • 由于Go的内置集合中没有Set的实现,可以用map[type]struct{}
    要求:
    1、元素的唯一性
    2、基本操作:添加、删除、判断是否存在、统计元素数量
    3、可遍历集合
//声明Set
type Set struct {
   //利用map,实现的Set集合
   MapSet map[string]struct{}
}
//新增
func (s *Set) add(val string) {
   s.MapSet[val] = struct{}{}
}
//删除
func (s *Set) delete(val string) {
   delete(s.MapSet, val)
}
//是否存在
func (s *Set) exist(val string) bool{
   if _, ok :=s.MapSet[val]; !ok {
      return false
   }
   return true
}
//计数
func (s *Set) count(val string) int {
   return len(s.MapSet)
}
//遍历:直接for遍历s.MapSet
posted @ 2023-12-10 19:08  _Eternity味道  Views(33)  Comments(0Edit  收藏  举报