有没有类似Python中'Set'的Go集合?
替代方案:
- 有没有在Go中实现集合的简单方法?
- 是否有任何方法可以消除切片中的重复项?
有没有类似Python中'Set'的Go集合?
替代方案:
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)
}
我认为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)
}
}
如果你考虑内存因素,使用它可能不太容易,但它可以占用更少的内存。
目前在golang中没有固定的实现。您需要自己完成或获取第三方库。此外,这里有一篇不错的博客文章:
https://www.openmymind.net/2011/7/15/Learning-Go-By-Benchmarking-Set-Implementation/
bool
类型会有额外的好处,因为当您索引一个不存在的键时,它将返回值类型的零值,对于布尔值来说是 false,这样您就可以通过索引测试元素是否存在。 - newacct