Go 中存在集合吗? (就像Python一样)

问题描述 投票:0回答:4

Python 中是否有类似 Set 的 Go 集合?

替代方案:

  • 在 Go 中是否有一种简单的方法来实现 Sets?
  • 有什么方法可以消除切片中的重复项吗?
collections set go
4个回答
15
投票

您可以只拥有一个

map[whatevertype]bool
并将值设置为
true
。您可以将切片中的每个元素添加为映射键,然后使用
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)
}

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
投票

目前 golang 中还没有固定的实现。您需要自己完成或获取第三方库。这里还有一篇不错的博客文章:

https://www.openmymind.net/2011/7/15/Learning-Go-By-Benchmarking-Set-Implementation/


0
投票

您可以检查这个实现Python设置功能的库 https://github.com/deckarep/golang-set

© www.soinside.com 2019 - 2024. All rights reserved.