Go Reference ยท Built-in Functions
Go max() and min() functions
Reference for Go's built-in max() and min(): compare several numbers or strings, the NaN and negative-zero rules, mixed constants and the slices package.
max() and min() return the largest and smallest of their arguments. They became built-in functions in Go 1.21, so you no longer need to write a helper such as func maxInt(a, b int) int. They accept two or more arguments of any ordered type: integers, floats and strings.
All arguments must have the same type (or be untyped constants that fit). If every argument is a constant, the result is a constant too.
fmt.Println(max(3, 9, 4), min(2.5, 1.5), max("pear", "apple")) // 9 1.5 pear
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func max[T cmp.Ordered](x T, y ...T) T func min[T cmp.Ordered](x T, y ...T) T
(Notation only: the built-ins are not generic functions you can reference or pass around.)
| Name | Description |
|---|---|
x, y... |
One or more values of the same ordered type. |
Returns: the largest (max) or smallest (min) argument.
Edge cases:
- If any floating-point argument is
NaN, the result isNaN. - For floats,
-0.0is considered smaller than+0.0. - Strings compare byte by byte (lexical order).
- A call with no arguments, or mixing types such as
intandfloat64variables, is a compile error.
Usage notes
- Built-in, not a package function. You cannot assign
maxto a variable or pass it to another function; wrap it in a function literal if you need to. - Clamping a value into a range is
min(max(v, lo), hi). - Mixed constants:
max(1, 2.5)is fine and gives the untyped constant2.5. With typed variables, convert first. - Slices: to find the extreme of a slice use
slices.Max()andslices.Min(), which panic on an empty slice. - Shadowing: programs written before Go 1.21 sometimes declare their own
maxormin. That still compiles (the local name wins), but you may delete the helper. - Evaluation: every argument is evaluated, in order, before comparing.
- Not available with
go 1.20or older ingo.mod; the language version of the module decides.