是否有任何类似于 Python 中的“Set”的 Go 集合?
备择方案:
最佳答案
你可以只拥有一个 map[whatevertype]bool
并将值设置为 true
。您可以将 slice 中的每个元素添加为映射键,然后使用 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)
}
关于collections - Go中存在集合吗? (就像在 Python 中一样),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7042250/