Go: Compute min and max

Integers

Go has no built-in min or max library functions for integers. It is simple to write your own:

// Min returns the smaller of x or y.
func Min(x, y int) int {
	if x > y {
		return y
	}
	return x
}

// Max returns the larger of x or y.
func Max(x, y int) int {
	if x < y {
		return y
	}
	return x
}

Floats

For floats, use math.Min and math.Max from the standard library:

// Min returns the smaller of x or y.
func Min(x, y float64) float64

// Max returns the larger of x or y. 
func Max(x, y float64) float64

Note the special cases:

Min(x, -Inf) = Min(-Inf, x) = -Inf
Min(x, NaN) = Min(NaN, x) = NaN
Min(-0, ±0) = Min(±0, -0) = -0

Max(x, +Inf) = Max(+Inf, x) = +Inf
Max(x, NaN) = Max(NaN, x) = NaN
Max(+0, ±0) = Max(±0, +0) = +0
Max(-0, -0) = -0

Comments