There are discussions of adding a generic version now: https://github.com/golang/go/issues/58146 https://github.com/golang/go/issues/58559 Answer from earthboundkid on reddit.com
🌐
IncludeHelp
includehelp.com › golang › math-max-function-with-examples.aspx
Golang math.Max() Function with Examples
Max(x, +Inf) = Max(+Inf, x) = +Inf If any of the parameter is positive infinity, the function returns +Inf.
Discussions

Min/Max for integers?
There are discussions of adding a generic version now: https://github.com/golang/go/issues/58146 https://github.com/golang/go/issues/58559 More on reddit.com
🌐 r/golang
78
42
April 5, 2023
Writing a function that returns the max value of a type [~float64 | ~uint | ~int T]
I would just use reflection here. var maxes = [...]any{ reflect.Int: math.MaxInt, reflect.Uint8: math.MaxUint8, reflect.Uint64: uint64(math.MaxUint64), reflect.Float64: math.MaxFloat64, } func Max[T cmp.Ordered]() T { typ := reflect.TypeFor[T]() v := maxes[typ.Kind()] val := reflect.ValueOf(v).Convert(typ) return val.Interface().(T) } func main() { type myInt uint8 fmt.Println(Max[int]()) fmt.Println(Max[float64]()) fmt.Println(Max[uint64]()) fmt.Println(Max[myInt]()) } More on reddit.com
🌐 r/golang
11
23
March 17, 2024
🌐
Go Packages
pkg.go.dev › math
math package - math - Go Packages
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 · Note that this differs from the built-in function max when called with NaN and +Inf.
🌐
YourBasic
yourbasic.org › golang › max-min-function
Compute max of two ints/floats · YourBasic Go
// Max returns the larger of x or y. func Max(x, y int64) int64 { if x < y { return y } return x } // Min returns the smaller of x or y. func Min(x, y int64) int64 { if x > y { return y } return x } For floats, use math.Max and math.Min.
🌐
DEV Community
dev.to › sw360cab › built-in-min-and-max-methods-in-go-121-24ph
Built-in min() and max() methods in Go 1.21 - DEV Community
April 24, 2024 - const MAX_TITLE_LENGTH int = 50 // a placeholder title var title string = "..." // the given title titleMaxLength := int( math.Min( float64(MAX_TITLE_LENGTH), float64(len(title)) ) ) croppedTitle := title[:titleMaxLength]
Top answer
1 of 9
184

Starting with Go 1.21, min and max are available as builtins and you do not need to write them at all. (Thanks @ufukty for highlighting this in a comment.)

I'm leaving the previous content below in case someone needs a different simple generic function that isn't built in or can otherwise use the historical answers.


Until Go 1.18 a one-off function was the standard way; for example, the stdlib's sort.go does it near the top of the file:

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

You might still want or need to use this approach so your code works on Go versions below 1.18!

Starting with Go 1.18, you can write a generic min function which is just as efficient at run time as the hand-coded single-type version, but works with any type with < and > operators:

func minT constraints.Ordered T {
    if a < b {
        return a
    }
    return b
}

func main() {
    fmt.Println(min(1, 2))
    fmt.Println(min(1.5, 2.5))
    fmt.Println(min("Hello", "世界"))
}

There's been discussion of updating the stdlib to add generic versions of existing functions, but if that happens it won't be until a later version.

math.Min(2, 3) happened to work because numeric constants in Go are untyped. Beware of treating float64s as a universal number type in general, though, since integers above 2^53 will get rounded if converted to float64.

2 of 9
23

There is no built-in min or max function for integers, but it’s simple to write your own. Thanks to support for variadic functions we can even compare more integers with just one call:

func MinOf(vars ...int) int {
    min := vars[0]

    for _, i := range vars {
        if min > i {
            min = i
        }
    }

    return min
}

Usage:

MinOf(3, 9, 6, 2)

Similarly here is the max function:

func MaxOf(vars ...int) int {
    max := vars[0]

    for _, i := range vars {
        if max < i {
            max = i
        }
    }

    return max
}
🌐
GeeksforGeeks
geeksforgeeks.org › go language › finding-maximum-of-two-numbers-in-golang
Finding Maximum of Two Numbers in Golang - GeeksforGeeks
April 28, 2025 - Go language provides inbuilt support ... the help of the math package. You can find the largest number among the given two numbers with the help of Max() function provided by the math package....
Find elsewhere
🌐
ZetCode
zetcode.com › golang › builtins-max
Understanding the max Function in Golang
May 8, 2025 - The max function is used to find the largest value among its arguments.
🌐
Educative
educative.io › answers › how-to-find-maximum-and-minimum-elements-in-an-array-in-go
How to find maximum and minimum elements in an array in Go
Then, we iterate through the remaining elements, updating the maximum and minimum values whenever a value lower than the current minimum or higher than the current maximum is encountered. ... Line 7: The findMaxMin() the function takes an integer array as input and returns the maximum and minimum values.
🌐
Gopher Coding
gophercoding.com › using-min-max-on-slice
Find the Min or Max Value in a Slice (New to Go 1.21) · Gopher Coding
January 17, 2024 - <p>The latest Go release, 1.21, has introduced two new built-in functions: <code>min()</code> and <code>max()</code>. These functions have long been used in many other languages, such as Python and JavaScript, and are now welcome additions to Go.</p> <p>The min() and max() functions have been introduced to simplify the process of finding the smallest and largest numbers in a set, respectively.
🌐
Medium
medium.com › gopher-time › go-1-21-new-built-ins-min-max-clear-explored-cda29ee56f22
Go 1.21: New Built-ins — min, max, clear Explored | by Adam Szpilewicz | Gopher Time | Medium
August 5, 2023 - The min function calculates the smallest value among a fixed number of ordered type arguments. There must be at least one argument… ... Backend software / data engineer working with rust, golang and python.
🌐
Olontsev
olontsev.io › new-min-and-max-built-in-functions-in-go-1-21
New min and max built-in functions in Go 1.21 – Sergey Olontsev
August 9, 2023 - Both functions accept values of an ordered type: integers, floats, or strings (or their derived types) and at least one argument should be specified. minValue := min(4, 8, 1) // min, integers fmt.Println(minValue) // 1 maxValue := max(4, 8, 1) // max, integers fmt.Println(maxValue) //8 minFloat := min(1.23, 0.99, 16.78) // min, floats fmt.Println(minFloat) // 0.99 minX := min(1.23, 2, 99, 0.5) // integers and floats fmt.Println(minX) // 0.5, float maxString := max("b", "abc", "x", "pq", "qp") // max, strings fmt.Println(maxString) // "x" type MyInt int a := MyInt(6) b := MyInt(78) c := max(a, b) fmt.Println(c) // 78
🌐
gogolok
gogolok.gitlab.io › posts › go-1-21-min-max
Built-in min and max functions in Go 1.21 · gogolok
August 8, 2023 - Go 1.21 brings the two built-in functions min and max to compute the smallest or largest value of a fixed number of arguments of ordered types. Only a fixed number of arguments is supported. Go needs to know the number of arguments at compile time. For string arguments the result for min is the first argument with the smallest (or for max, largest) value, compared lexically byte-wise.
🌐
TutorialsPoint
tutorialspoint.com › finding-maximum-of-two-numbers-in-golang
Finding Maximum of Two Numbers in Golang
April 12, 2023 - In the above code, we declare a ... value. Golang's math package provides a Max function that takes two float64 arguments and returns the maximum value....
🌐
ITNEXT
itnext.io › generics-in-golang-1-18-no-need-to-write-max-min-anymore-maybe-d79f3392ca38
Generics in Golang 1.18, no need to write max / min anymore (maybe) | by Jerome Wu | ITNEXT
June 10, 2021 - The root cause of the tediousness of this task is the lack of generics in golang which means you can not implement a max/min function which accepts both integer and float numbers.
🌐
Go
go.dev › play › p › qeElniC-Nin
Go Playground - The Go Programming Language
If the program contains tests or examples and no main function, the service runs the tests.
🌐
Reddit
reddit.com › r/golang › writing a function that returns the max value of a type [~float64 | ~uint | ~int t]
r/golang on Reddit: Writing a function that returns the max value of a type [~float64 | ~uint | ~int T]
March 17, 2024 -

Today I was trying to write a generic function to return the maximum value for floats, ints and uints. It seems straightforward, right? It's not!

The function signature:

type Types interface {
    ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uint |
   	 ~int | ~int64 | ~int32 | ~int16 | ~int8 |
   	 ~float64 | ~float32
}

func infFor[T Types]() T

My first thought was to write a switch checking the type, like this:

func infFor[T Types]() T {
	var v T
	switch any(v).T {
	case float64:
    	return T(math.Inf(1))
	case int8:
    	return T(math.MaxInt8)
	...
	}
}

But this doesn't work for user defined types (type myInt int).

Then I tried to split the function in two parts, check if T is a float or (u)int, this makes the job easier.

func infFor[T Types]() T {
    // Check if T is a float.
    var f float64 = 1.5
    if float64(T(f)) == f {
   	 return T(math.Inf(1))
    }
    
	// Handle (u)ints ...
}

Converting 1.5 to an integer type will truncate the value and then float64(T(f)) == f is false.

The value 1.5 is important because it can be represented both by float64 and float32, 1.1 can't.

After the check we know the value is an integer, but the compiler doesn't, so we can't use bit arithmetic. The solution I found is to check when the value overflows.

This is the final version:

func infFor[T Types]() T {
    // Check if T is a float.
    var f float64 = 1.5
    if float64(T(f)) == f {
   	 return T(math.Inf(1))
    }

    maxValues := [...]uint64{
   	 math.MaxInt8,
   	 math.MaxUint8,
   	 math.MaxInt16,
   	 math.MaxUint16,
   	 math.MaxInt32,
   	 math.MaxUint32,
   	 math.MaxInt64,
   	 math.MaxUint64,
    }

    var v T
    // Check when v overflows.
    for i := 0; v+1 > 0; i++ {
   	 v = T(maxValues[i])
    }

    return v
}
🌐
Programming.Guide
programming.guide › go › max-min-function.html
Go: Compute min and max | Programming.Guide
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