Go 1.27 reference · Built-in Functions
Go min and max Function
Return the smallest or largest of their arguments for any ordered type (numbers and strings); built in since Go 1.21.
Go 1.27 Since 1.21
Syntax
func min[T cmp.Ordered](x T, y ...T) T func max[T cmp.Ordered](x T, y ...T) T
Parameters
| Parameter | Description |
|---|---|
x, y... |
One or more values of the same ordered type. |
Examples
package main
import "fmt"
func main() {
fmt.Println(min(3, 1, 2), max(2.5, 7.0))
fmt.Println(min("pear", "apple"))
page := 0
page = max(page, 1) // clamp to at least 1
limit := min(500, 100)
fmt.Println(page, limit)
}
Output
1 7 apple 1 100
Run this on your computer — see “Get Started” for setup.
package main
import (
"fmt"
"slices"
)
func main() {
prices := []float64{8.5, 24, 3.2}
fmt.Println(slices.Min(prices), slices.Max(prices))
}
Output
3.2 24
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Go 1.21 | Added |
Related
slices.Sort and slices.SortFunc· Sort a slice in place in ascending order, or with a comparison function for custom and multi-key ordering.