Go数据结构--Set

523 阅读1分钟

在Go中没有像Python一样,有set 这样数据结构。这边用到一个开源库 golang-set 地址:github.com/deckarep/go… 。你要是自己开心 手撸一个也可以。

综合例子


package main

import (
  "fmt"
  mapset "github.com/deckarep/golang-set/v2" //一定要导对包
)

func main() {
  // Create a string-based set of required classes.
  required := mapset.NewSet[string]()
  required.Add("cooking")
  required.Add("english")
  required.Add("math")
  required.Add("biology")

  // Create a string-based set of science classes.
  sciences := mapset.NewSet[string]()
  sciences.Add("biology")
  sciences.Add("chemistry")
  
  // Create a string-based set of electives.
  electives := mapset.NewSet[string]()
  electives.Add("welding")
  electives.Add("music")
  electives.Add("automotive")

  // Create a string-based set of bonus programming classes.
  bonus := mapset.NewSet[string]()
  bonus.Add("beginner go")
  bonus.Add("python for dummies")
}

创建一组所有唯一类。Sets 会自动去重相同的数据

all := required
    .Union(sciences)
    .Union(electives)
    .Union(bonus)
  
  fmt.Println(all)

输出

Set{cooking, english, math, chemistry, welding, biology, music, automotive, beginner go, python for dummies}

包含关系

result := sciences.Contains("cooking")
fmt.Println(result)

输出

false

差集

notScience := all.Difference(sciences)
fmt.Println(notScience)
Set{ music, automotive, beginner go, python for dummies, cooking, english, math, welding }

交集

reqScience := sciences.Intersect(required)

输出:

Set{biology}