Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between generic and non-generic use of interfaces?

In the new Type Parameters Design Draft, you can now apply an interface constraint to a generic function:

func prettyPrint[T Stringer](s T) string {
    ...
}

But, this was already possible by using an interface parameter without generics:

func prettyPrint(s Stringer) string {
    ...
}

What's the difference between using the first and using the second?

like image 413
TheEnvironmentalist Avatar asked Jan 20 '21 02:01

TheEnvironmentalist


1 Answers

I assume the question refers to the latest draft of the Type Parameters proposal, which may end up in Go in 1.18.


The first is parametric polymorphism. The compiler verifies that the constraint is satisfied, and then generates code that takes a statically-known type. Importantly, it's not boxed.

The second is runtime polymorphism. It takes a type that's unknown at compile time (the only thing known is that it implements the interface) and works on a boxed interface pointer.

Performance considerations aside, in this simple case you can use either approach. Generics really help with the more complicated cases where the current tools don't work well.

like image 122
Eli Bendersky Avatar answered Nov 24 '22 18:11

Eli Bendersky