在Go中是否存在集合?(类似于Python)

13

有没有类似Python中'Set'的Go集合?

替代方案:

  • 有没有在Go中实现集合的简单方法?
  • 是否有任何方法可以消除切片中的重复项?
3个回答

15
你可以使用一个map[任意类型] bool来将值设置为true。你可以将切片中的每个元素作为map的键,然后使用range只获取唯一的元素。
package main
import "fmt"
func main() {
    m := make(map[string]bool)
    s := make([]string, 0)
    s = append(s, "foo")
    s = append(s, "foo")
    s = append(s, "foo")
    s = append(s, "bar")
    s = append(s, "bar")
    for _, r := range s {
        m[r] = true
    }
    s = make([]string, 0)
    for k, _ := range m {
        s = append(s, k)
    }
    fmt.Printf("%v\n", s)
}

3
我想补充一下,实际上您可以使用任何任意类型作为值,因为您不需要关心它。但是,使用一个始终设置为 true 的 bool 类型会有额外的好处,因为当您索引一个不存在的键时,它将返回值类型的零值,对于布尔值来说是 false,这样您就可以通过索引测试元素是否存在。 - newacct

2

我认为map[T]bool是最好的选择,但另一个选择是map[T]struct{}

package main

func main() {
   { // example 1
      s := make(map[string]struct{})
      s["north"] = struct{}{}
      s["south"] = struct{}{}
      _, ok := s["north"]
      println(ok)
   }
   { // example 2
      s := map[string]struct{}{
         "north": {}, "south": {},
      }
      _, ok := s["north"]
      println(ok)
   }
}

如果你考虑内存因素,使用它可能不太容易,但它可以占用更少的内存。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接