golang实现集合

在 Go 语言中,可以使用 map、slice 或者自定义结构体来实现集合(Set)的功能。集合是一个无序的、不包含重复元素的序列。以下是使用 map 实现集合的一个简单示例:
package main

import “fmt”

// Set 是一个集合,使用 map 来存储元素,确保元素的唯一性
type Set map[interface{}]bool

// NewSet 创建一个新的集合
func NewSet(elements …interface{}) Set {
s := Set{}
for _, e := range elements {
s.Add(e)
}
return s
}

// Add 向集合中添加一个元素
func (s Set) Add(element interface{}) {
s[element] = true
}

// Remove 从集合中移除一个元素
func (s Set) Remove(element interface{}) {
delete(s, element)
}

// Contains 检查集合中是否包含某个元素
func (s Set) Contains(element interface{}) bool {
_, exists := s[element]
return exists
}

// Size 返回集合中的元素数量
func (s Set) Size() int {
return len(s)
}

// Intersection 返回两个集合的交集
func (s Set) Intersection(other Set) Set {
newSet := NewSet()
for elem := range s {
if other.Contains(elem) {
newSet.Add(elem)
}
}
return newSet
}

// Union 返回两个集合的并集
func (s Set) Union(other Set) Set {
newSet := NewSet()
for elem := range s {
newSet.Add(elem)
}
for elem := range other {
newSet.Add(elem)
}
return newSet
}

// Difference 返回两个集合的差集
func (s Set) Difference(other Set) Set {
newSet := NewSet()
for elem := range s {
if !other.Contains(elem) {
newSet.Add(elem)
}
}
return newSet
}

func main() {
s1 := NewSet(1, 2, 3, 4)
s2 := NewSet(3, 4, 5, 6)

fmt.Println(“Set 1:”, s1)
fmt.Println(“Set 2:”, s2)

s1.Add(5)
fmt.Println(“After adding 5 to Set 1:”, s1)

s1.Remove(2)
fmt.Println(“After removing 2 from Set 1:”, s1)

fmt.Println(“Contains 4:”, s1.Contains(4))
fmt.Println(“Size of Set 1:”, s1.Size())

intersection := s1.Intersection(s2)
fmt.Println(“Intersection:”, intersection)

union := s1.Union(s2)
fmt.Println(“Union:”, union)

difference := s1.Difference(s2)
fmt.Println(“Difference:”, difference)
}
这个示例定义了一个
Set
类型,它是一个 map,其中 key 是集合中的元素,value 是布尔值(虽然在这个实现中我们不使用它)。我们定义了
Add
、
Remove
、
Contains
、
Size
、
Intersection
、
Union
和
Difference
等方法来实现集合的基本操作。
请注意,这个实现使用了
interface{}
类型来存储集合中的元素,这意味着它可以存储任何类型的元素,但同时也失去了类型安全。在实际应用中,你可能需要根据具体需求来定义更严格的类型约束。