4 ms·
You can instantiate it with [any] then use whatever you'd like https://go.dev/play/p/JeSuB_xYNEf https://go.dev/play/p/JeSuB_xYNEf, but I don't think it would w
by thegeekpirate 4y ago
You can instantiate it with [any] then use whatever you'd like https://go.dev/play/p/JeSuB_xYNEf 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.
- drdaeman 4y agoOooh. 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 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 https://go.dev/play/p/acwjxdpHTJO
- tsimionescu 4y agoSure, 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.