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

发布于 2024-11-29 07:31:39 字数 121 浏览 1 评论 0原文

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

替代方案:

  • 是否有一种简单的方法在 Go 中实现 Sets?
  • 有什么方法可以消除切片中的重复项吗?

Is there any Go collection similar to 'Set's in python?

alternatives:

  • Is there an easy way of implementing Sets in Go?
  • Is there any method to eliminate duplicates in a slice?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

在梵高的星空下 2024-12-06 07:31:39

您可以只使用 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)
}

You could just have a map[whatevertype]bool and set the value to true. You could add every element in a slice as a map key, then use a range to get only the unique ones back out.

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)
}
稀香 2024-12-06 07:31:39

我认为 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)
   }
}

它不太容易使用,但如果这对您来说是一个因素的话,它会占用更少的内存。

I think the map[T]bool is the best option, but another option is
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)
   }
}

it's not as easy to work with, but it takes up less memory if that is a factor for you.

又爬满兰若 2024-12-06 07:31:39

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

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

There is no set implementation in golang at this point. You'll need to do it yourself or get a third party lib. Also here is a nice blog post:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文