6 ms·
Would you use generics to write the same implementation of min/max for integers and floats?
by horsemans 5y ago
Would you use generics to write the same implementation of min/max for integers and floats?
- grey-area 5y agoYou 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.
- qaq 5y agoThe fact that you would not need a separate one for each of the: uint8 , uint16 , uint32 , uint64 , int8 , int16 , int32, int64 is not enough ?
- Groxx 5y agoAbsolutely, yes. It's downright trivial: https://gotipplay.golang.org/p/XF6wM3JF2QM https://gotipplay.golang.org/p/XF6wM3JF2QM From https://itnext.io/generics-in-golang-1-18-no-need-to-write-max-min-anymore-maybe-d79f3392ca38 https://itnext.io/generics-in-golang-1-18-no-need-to-write-m...
- danachow 5y agoThis is a joke, right? Your trivial implementation isn't even correct.
- Jtsummers 5y agohttps://gotipplay.golang.org/p/N2v8aB1tUtN 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.
- Groxx 5y agoyeah, it's just old. the `~int | ~float32 | etc` syntax is relatively recent.
- deleted 5y ago[deleted]
- danachow 5y agoWhy 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.