top | item 5821150

(no title)

JeanPierre | 12 years ago

I would like to add on to this:

Generics may not be the correct solution, but I would really like a way to make collections which are general enough to be used by any datatype. As of now, I cannot do that without doing the typical `interface{}` approach.

The built-in data structures + channels are able to handle this, but if I just want a set of elements, what do I do? Make a `map[foo] bool`? If I see such a piece of code in an unfamiliar code base, I have no idea whether to test for key existence or whether I have to test whether the bool is true. A generic set would leave me puzzled and type unsafe[1]: What types could possibly exist in this set? A set of foos is not that hard to comprehend, and is in fact very much more straightforward to understand than a generic set, which in unfamiliar code may contain anything, or a mapping from foos to bools.

[1]: Rob Pike mentions in http://www.youtube.com/watch?feature=player_detailpage&v... that type safety is of high importance for Golang, but how does one achieve that if all the different datatypes I implement/need use `interface {}` where I have to cast all values afterwards? That seems very type unsafe, from where I stand.

discuss

order

scarboy|12 years ago

You should be using map[T]struct{} for sets instead of bool. struct{}s use 0 bytes and there will be no confusion as to what the value is for.

mietek|12 years ago

Your puzzling "generic set" isn't what is usually meant by a generic set in a statically typed language.

A generic set would be defined disregarding the type of its elements: "set of ?s". However, a single instance of a generic set would only be allowed to contain members of a single type: "set of foos". This is called parametric polymorphism.