Like the question, How to create a set in Go?
For example in Python I can do set()
or {}
to create one that can hold any object. As far as I know there is no equivalent of a set in Go, but you have to use a map.
Is there an equivalent in Go that can hold multiple types? As I would do it?
Thank you!
As you say, go itself doesn't have such a collection type in its standard library, but you can create your own types based on native structures such as arrays, slices or maps.
Now I think there's no need to reinvent the wheel so you could just use a bookstore that already has all those structures.
https://github.com/Workiva/go-datastructures
Go doesn't have an implementation of a set as such within the standard package library, but...
In go there are interfaces https://tour.golang.org/methods/9 . They are useful for scenarios where you have functions or methods that must take arguments of multiple types. With this in mind it is possible to make a map that stores an interface (if you are looking for a set it is possible to use a map as such); for example here is a data mapping in JSON format:
Therefore, using a string or the data type that you deem convenient as a key, it is possible to map various types of data within the interface, be they string, int, map[string]interface{}, bool and even functions . To access these values, just use the corresponding key:
Now if this is not enough for what you need, you can always use an available implementation like the one mentioned above https://github.com/Workiva/go-datastructures or implement your own data structure package (why not) .
Cheers!