Hacker News new | ask | show | jobs
by horsemans 1647 days ago
Would you use generics to write the same implementation of min/max for integers and floats?
4 comments

This is a joke, right? Your trivial implementation isn't even correct.
https://gotipplay.golang.org/p/N2v8aB1tUtN

Is this one better? It does run and doesn't rely on casting (not sure why GP's source took that route, it was lossy and kind of dumb). I suspect the compilation problem was because of a change in the syntax between when that was created and today.

yeah, it's just old. the `~int | ~float32 | etc` syntax is relatively recent.
Why not? You later seem to think that this would require reflection - but that makes it apparent you don't understand how generics work in a language. They're used at compile time - to avoid runtime checking.
You certainly might use them to write a facade which made life easier for consumers of the math pkg and accept floats,ints or uints even if behind the scenes it splits into different implementations.
I would not be very happy if every time I called math.Min, I was also, under the hood, calling reflect.TypeOf.
The whole point of generics is to avoid this - why do you think you would have to use reflection?
The fact that you would not need a separate one for each of the: uint8 , uint16 , uint32 , uint64 , int8 , int16 , int32, int64 is not enough ?