Hacker News new | ask | show | jobs
by tubby12345 1652 days ago
>One annoying bit about Go's generics is that you can't use type parameters in methods.

i haven't written go in a long time (generics would/could get me to go back to it) but are you saying that functions can't be generic? or is members here vernacular for class (struct?) associated functions? i thought those were called "receivers", which you mention further down. so it looks to me like you're saying that functions can't be generic. to which i ask: wtf is the point of generics when functions can't be generic...?

1 comments

You can use type parameters in functions, but not methods. Methods are functions which have a receiver, so:

    // This is a function, you can use type parameters here:
    func Foo[T any](g T) { ... }
    
    type bar struct {}

    // This is a method, you can't use type parameters here:
    func (b bar) Foo[T any](g T) { ... }
In the second case, "Foo" is a method which has a "bar" instance as a receiver.

I've edited my original post to make it a bit clearer.

Doesn't C++ have a similar restriction, in that virtual methods cannot be templates? And in Go, with its dependence on interfaces everywhere, every method is the equivalent of /comparable to a C++ virtual method.
Yes, and you are right, Go interfaces are similar to pure virtual base classes in C++ (to the extent of virtual dispatch being discussed).
so does this mean there are no generic structs in generic go?
You can do

    type X[T any] struct{}
    func (x *X[T]) Method() {}
just fine. What you can't do is

    func (x *X[T]) Method[T2 any]() {}
Not saying mixing OO and generics could never have any merit, but.. Isn't a method just a function having an object as first parameter. Does Go change this beyond "syntactic sugar" somehow? Been a while from coding Go, so interested to hear.

The rationale seems to me that generics be functions first (ok, procedural), and not complecting it with objects and OO too much, whatever that mix could mean..

> Isn't a method just a function having an object as first parameter.

Differences:

- Methods must be defined in the same package as the receiver.

- Methods can be used to implement interfaces.

- Methods can be discovered dynamically by inspecting the type of the receiver (either through reflection or with a dynamic cast).

In other words, methods cannot introduce generic types.