DEV Community

Sergio Matone
Sergio Matone

Posted on

7

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

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]
Enter fullscreen mode Exit fullscreen mode

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)) )
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay