7. Generics
The Go 1.18 release (February 2022) adds support for generics. In the following section, we will take a look at the new language feature but we will not cover every detail.
Why do we need Generics
Imagine you implement a function contains to check wheter a certain item is in a list:
func contains(list []int, item int) bool {
for _, current := range list {
if current == item {
return true
}
}
return false
}
The function above only works for slices of the type int. If you need the same logic for strings you have to implement a new function which would look exactly the same apart from the types in the function signature. If the function is in the same package you also have to choose a different name.
func containsString(list []string, item string) bool {
for _, current := range list {
if current == item {
return true
}
}
return false
}
Since Go 1.18 we can write the contains function in a generic way:
| |
Output:
true
false
true
false
Other examples
Max Function
In this example we create a max function which returns the bigger of two values. To specify the constraint we use the Ordered interface from the constraints
package:
| |
Output:
42
3.14
Generic struct
We can also use generics to parametrize structs:
type LinkedList[T any] struct {
head *Node[T]
}
type Node[T any] struct {
item T
next *Node[T]
}
Links
Official Go resources about the topic:
- An Introduction To Generics
- Tutorial: Getting started with generics
- When To Use Generics
- Type Parameters Proposal
Other blog posts about the topic: