Re:Go generics are not bad
by thegeekpirate on Friday July 08, 2022 @09:25PM
(#32030345)
You can instantiate it with [any] then use whatever you'd like https://go.dev/play/p/JeSuB_xYNEf, but I don't think it would work with a type constraint such as `int|string`, which would be a fair point.
[ Parent
| on HN ]
Re:Go generics are not bad
by tsimionescu on Saturday July 09, 2022 @01:43AM
(#32032155)
Sure, but it's no longer generic, you're just using runtime types again.
This is extremely important, because it means `func (someType[T any]) foo(T x) T`, `x.foo(1)` would return `any`, not `int` like a generic function would.
In fact, if you're going to instantiate a generic type parameter with `any`, I would very much doubt you wanted a generic type in the first place.
Oooh. My bad. Thank you! I honestly thought that wasn't possible at all. Today I learned.
However, it won't work for return values, right? Because e.g. `func (some something[T]) hi(b T) T` would return `any` and not whatever it was provided (`int` or `string` respectively).
https://go.dev/play/p/IYoPUQg04sg
Also, I don't think this can work well with types narrower/fancier than `any`, e.g. I had trouble figuring out how to deal with
type IntOrString interface {
int | string
}
type something[T IntOrString] int
https://go.dev/play/p/acwjxdpHTJO