Is there any Go collection similar to 'Set's in python?
alternatives:
Although Go doesn't have sets natively, we can make use of maps to act the same way. We were able to execute all operations that are characteristic of a set, with the same time complexity of O(1) for adding and removing members from a set.
Creating Python Sets It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements. Try the following examples as well.
Set Items. Items of a set in python are immutable (unchangeable), do not duplicate values, and unordered.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With