Getting the minimum and maximum from a slice are some of the simplest functions that are written by developers during everyday coding. The problem is that when you wanted to get the minimum or maximum from int
and float64
slices, up until now, you had to write two functions for each slice type. However, since version 1.18, Go has introduced the much-anticipated Generics, and you can now write single min()
and max()
functions that work for any ordered type.
This article is part of the Introduction to Go Generics series. Go here to see more.
|
|
Generic functions need type parameters that describe types that are allowed for a given function and provide the type label used in the function body. As you can see in the example, they are declared in square brackets after the name of a function:
func name[TypeLabel Constraints](...) {
...
}
In the min()
and max()
functions we declare a type parameter T
with constraints.Ordered
constraint. It guarantees that the functions work only for slice types that support the operators <
, <=
, >=
, >
. The rest of the functions are pretty straightforward. They take a slice of type T
as an argument, return a zero value for a given type if the slice has size 0, and find the minimum or maximum of the slice in a loop. As a result, they return a single min or max value of type T
.
From the example above, we get the following output:
1
8.2
It is really exciting how, thanks to Generics, it is possible to make things that were not possible before in Go. We are sure that this feature will improve the code quality of any Go project 😊.