Golang Generics For Advanced Golang Developers


Improve speed with generics in Golang

The author of this article is not going to try to teach you generics in this story, but instead assume you know about generics, parameterized types, or template-based Golang programming already.

This shows the basics of Golang Generics. Type parameters are constrained by interfaces. That means you can demand that your type parameter T implements certain methods or are of certain types. Here we specify that the interface Number matches anything that is a intint64 or a float64.

type Number interface {
int | int64 | float64
}

func Sum[T Number](numbers []T) T {
var total T
for _, x := range numbers {
total += x
}
return total
}

Try out this example in the Golang Playground.

Golang’s Generic Types

It is important to note that when defining parameterized types, the methods the golang developer add cannot introduce new type parameters. We can only use the ones defined in the type definition. Hence, you will notice for Push and Pop that we don’t specify constraints on T.

There is nothing in the method definitions that hints at T being a type parameter. Instead, Go derives that knowledge from the type definition.