Generics and methods on predeclared types

105 views
Skip to first unread message

Markus Heukelom

unread,
Nov 10, 2020, 8:36:48 AM11/10/20
to golang-nuts
Currently the predeclared types (int, bool, float32, string, etc) do not have any methods on them. It appears to me that if they would, the generic implementation for math.Min/Max etc could do without 'types' in interfaces (as is currently proposed).

For example:

type Sortable[T any] interface {
Compare(T other) int
}

Suppose that int, float64, string etc all predeclare the Compare(T) int method. Then

func Max[T Sortable[T]](a, b T) T {
if a.Compare(b) >= 0 {
return a
}
return b
}

Is this something that was considered or is this just a bad idea? (It would require that all predeclared types expose most operators in some method form). 

One obvious benefit is that Max works for any user type as well (instead of only predeclared types). Another benefit is that the interface{} concept would not need to be extended (at least for the purpose of generics) with type lists.

Markus


Ian Lance Taylor

unread,
Nov 10, 2020, 10:05:08 AM11/10/20
to Markus Heukelom, golang-nuts
It's been considered. There are various concerns.

Once you decide to add methods to predeclared types, how do you decide
which methods to add? When do you stop?

Normally if I write "type MyInt1 MyInt2" then MyInt1 does not pick up
any methods that are defined on MyInt2. But if I write "type MyInt
int" I probably do want to pick methods like your suggested Compare
method. Why do methods on predeclared types work differently, and how
exactly do they work?

In general the point of methods is to satisfy interfaces. But a
method like "Compare(int16) int" doesn't satisfy any plausible
interfaces. And a method like "Compare(interface{}) int" doesn't
correspond to any language operation and it's not immediately obvious
how it should handle comparisons between values of different types,
e.g., with different signedness.

It's true that such methods could be implemented by type-parameterized
interfaces, as you suggest. And many people have investigated whether
methods can be defined on predeclared types as part of defining
generics. Some problems I've seen with that are 1) if you want to
support all operations, you realize that the language is not all that
regular; 2) you wind up with a large number of new names in the
language, all of which have to be learned by all Go programmers.

Thanks for the note.

Ian
Reply all
Reply to author
Forward
0 new messages