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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
x, y... One or more values of the same ordered type.

Examples

Example 1
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.

For slices, use slices.Min and slices.Max
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

VersionChange
Go 1.21Added

Was this page helpful?