Hacker News new | ask | show | jobs
by binarycrusader 4434 days ago
I'm not asking for generics, but I really want an equivalent to Python's set data type for strings and numbers at the leas built-in. I'm aware of golang set on GitHub and the gen project as well, but I'm shocked that Go doesn't have an equivalent to the set data type yet.

I'm open to suggestions.

3 comments

    s := make(map[string]struct{})
    s["foo"] = struct{}{}
    if _, ok := s["foo"]; ok {
      // exists
    }
There are varying amounts of fluff you can put on top of this, but that's the basic approach. Wrap it up in a type with methods if you're using it a lot in a program.

Perhaps you also want built-in union, intersection, difference, etc. I personally find I need a set with simple membership testing about 10x as often as I need more advanced set operations, so from my perspective it's fine to leave those to third-party libraries.

Yes, I was actually looking for the union intersection, etc. functionality. I use that extensively in the project I work on. And it's core enough that I want it in the language, not as a third-party add on because of the performance implications and because of things the language can enforce natively. The Python set data type really is great for a certain class of problems. In particular, graph analysis and traversal.
Lot's of libraries for this on Github; everone (myself included; plug: https://github.com/bulters/readyset) and his mother probably writes one at some point.
As I said, I really want to see it in the core language. Your point about "everone ... and his mother probably writes one at some point" seems like a strong point for just putting it into the language or primary implementation if it's such a common pattern.
I fully agree in this case. But am hestitant to call for the same treatment of e.g. A web framework.

Question to answer then is: Where does the plumbing stop and the kitchen begin?

In my opinion, we're talking about data types / data structures, which neatly avoids that discussion :-)
I tend to use map[string]interface{} when I need a set. It works okay.
struct{} is better because it doesn't do an allocating. See: https://github.com/fatih/set/blob/master/set_ts.go#L18
Why interface{}? You're storing a value (and using space for it) that you don't need.
Thanks, that does seems like a rather elegant, simple implementation. I still want to see it in the core language or primary implementation, but seeing the different ways people implement sets in Go is helpful because I'm certain there are pitfalls in doing so.