go用map实现set

package main

import "fmt"

func makeSet() *customSet {
    return &customSet{
        container: make(map[string]struct{}),
    }
}

type customSet struct {
    container map[string]struct{}
}

func (c *customSet) Exists(key string) bool {
    _, exists := c.container[key]
    return exists
}

func (c *customSet) Add(key string) {
    c.container[key] = struct{}{}
}

func (c *customSet) Remove(key string) error {
    _, exists := c.container[key]
    if !exists {
        return fmt.Errorf("Remove Error: Item doesn't exist in set")
    }
    delete(c.container, key)
    return nil
}

func (c *customSet) Size() int {
    return len(c.container)
}

func (c *customSet) Print() {
    for k, v := range c.container {
        fmt.Println(k, v)
    }
}

func main() {
    customSet := makeSet()
    fmt.Printf("Add: A
")
    customSet.Add("A")
    fmt.Printf("Add: B
")
    customSet.Add("B")
    fmt.Printf("Size: %d
", customSet.Size())
    fmt.Printf("C exists? %t
", customSet.Exists("C"))
    customSet.Print()
}
原文地址:https://www.cnblogs.com/donggongdechen/p/14710652.html