go实现set

package main

import (
    "fmt"
    "sync"
)

type object interface{}
type Set struct {
    m map[object]bool
    sync.RWMutex //线程安全实现,记录下
}

//初始化
func New() *Set {
    return &Set{
        m: map[object]bool{},
    }
}

func (s *Set) Add(item object) {
    s.Lock()
    defer s.Unlock()
    s.m[item] = true
}

func (s *Set) Remove(item object) {
    s.Lock()
    defer s.Unlock()
    delete(s.m, item)
}

func (s *Set) Clean() {
    s.m = map[object]bool{}
}
func (s *Set) Len() int {
    return len(s.m)
}

func (s *Set) Contains(item object) bool {
    _, ok := s.m[item];
    return ok
}

func (s *Set) IsEmpty() bool {
    fmt.Println(len(s.m))
    return len(s.m) > 0
}

func main() {
    s := New()
    fmt.Println(s.IsEmpty())
    s.Add("aaa")
    fmt.Println(s.IsEmpty())
    s.Add("1")
    s.Add("2")
    s.Add("3")
    fmt.Println(s.Contains("3"))
    //s.Clean()
    for key, _ := range s.m {
        fmt.Println("Key:", key)
    }
}

 

posted @ 2019-05-17 17:18  wujf  阅读(862)  评论(0编辑  收藏  举报