There are so many things I love about Go, but one thing that I've found slightly annoying is having to write my own min and max methods for comparable elements. Go is the 6th programming language I've worked with, but the first to not have built-in support for them. Previously, I've had to do something similar to:
func findMin(a, b int) int {
if a < b {
return a
}
return b
}
func findMax(a, b int) int {
if a > b {
return a
}
return b
}
a, b := 1, 2
fmt.Println(findMin(a,b)) // 1
fmt.Println(findMax(a,b)) // 2
When I first heard about generics coming to Go, my first thought was "finally, we'll have min and max". Now, it's officially part of the Go spec in version 1.21.
We can now call the built-in functions like so with any ordered type (int
, uint
, float
, string
):
a, b := 1, 2
fmt.Println(min(a, b)) // 1
fmt.Println(max(a, b)) // 2
Now we can put min
effort into getting max
results.