Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You can certainly use generic parameters in methods—the [T any] just has to be on SomeNonGenericType, even if it's not used inside the type itself https://rakyll.org/generics-facilititators


Yes, but that's completely different thing. If you move T you would change the semantics.

- func (self SomeType[T]) Foo(...) is a method for a class parametrized on T. So if you want foo.Foo(1) then it only works for foo that's SomeType[int]. You cannot then easily call foo.Foo("one") on the same instance.

- func (self SomeType) Foo[T any](...) - if that'd be a thing - would be a generic method on SomeType that works for any T. So you can foo.Foo(1) and foo.Foo("one") on the very next line and that would work.


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.


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




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: