Skip to content
Tutorials Center
My learning

Topics

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.

Go
fmt.Println(max(3, 9, 4), min(2.5, 1.5), max("pear", "apple"))
// 9 1.5 pear

Try it

Go Numbers, floats and strings

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.

Go NaN and signed zero

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

Go
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 is NaN.
  • For floats, -0.0 is considered smaller than +0.0.
  • Strings compare byte by byte (lexical order).
  • A call with no arguments, or mixing types such as int and float64 variables, is a compile error.

Usage notes

  • Built-in, not a package function. You cannot assign max to 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 constant 2.5. With typed variables, convert first.
  • Slices: to find the extreme of a slice use slices.Max() and slices.Min(), which panic on an empty slice.
  • Shadowing: programs written before Go 1.21 sometimes declare their own max or min. 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.20 or older in go.mod; the language version of the module decides.