Built-in min() and max() methods in Go 1.21

RMAG news

I recently realized that in Go 1.21 the built-in methods min() and max() where introduced, which allows you to get the min and max of a set of heterogeneous items. This is now doable thanks to the introduction of Generics in Go 1.18.

So, for example when I have a string, let’s say a title, and I want to get the substring which has a length gathered from the minimum value between a given number and the length of the string itself. Once I would have used the math.Min method, which requires two float64 types as parameters, and I would have done the following:

const MAX_TITLE_LENGTH int = 50

// a placeholder title
var title string = “…” // the given title

titleMaxLength := int(
math.Min( float64(MAX_TITLE_LENGTH), float64(len(title)) )
)

croppedTitle := title[:titleMaxLength]

Whereas now I can achieve the same by simplifying using built-in min() method, without casting over and over the operands:

titleMaxLength := min( MAX_TITLE_LENGTH, len((title)) )

If we check the definition of the method, there is another important thing to notice, the method is not limited to a pair of parameters, but it accepts an unlimited number of (homogeneous) parameters.

package builtin

func min[T cmp.Ordered](x T, y T) T

Note:
Even though we are already at Go 1.22, I realized a little late that this feature was actually introduced in Go 1.21. What should I say about that? It’s better late than never!

Leave a Reply

Your email address will not be published. Required fields are marked *