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?
Is there any Go collection similar to 'Set's in python?
alternatives:
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)
}
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.
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/