GoLang Max() and Min()

In this tutorial, we will learn how to find a max and min values of a two given numbers with the help of in-built methods of the GO.

In the Go Language Max() and Min() functions are used to find a max and min values of a two given numbers respectively, let us explore the uses cases of each separately with help of simple examples.

Max()

Max() will return the maximum value from the given two numbers.

Let the two numbers be a and b.

Syntax:


math.Max(a,b)

max function accepts two variables as a parameter for comparison.

Cases:

If a or b is positive Infinity, then the result is positive infinity (+Inf).

If a or b is NaN, then the result is NaN.

Max() :

To use the Max function, its required to import the "math" package.

Let us demonstrate the above-described cases with following examples.

Example 1:

CopiedCopy Code

package main

import (
	"fmt"
	"math"
)

func main() {

// let a is positive infinity
fmt.Println(math.Max(math.Inf(+6),4))

// let b is positive infinity
fmt.Println(math.Max(34,math.Inf(+6)))

// let a is NaN
fmt.Println(math.Max(math.NaN(),4))

// let b is NaN
fmt.Println(math.Max(100,math.NaN()))

}

Output:

CopiedCopy Code

+Inf
+Inf
NaN
NaN

Example 2: -

CopiedCopy Code

package main

import (
	"fmt"
	"math"
)

func main() {

// let a = 12, b=23
fmt.Println(math.Max(12,23))

// let a = 12, b=3
fmt.Println(math.Max(12,3))

// let a = 1, b=-1
fmt.Println(math.Max(1,-1))

}

Output:-

23 12 1

Explanation for the above examples output.

  1. Among 12 and 23, 23 is the maximum.
  2. Among 12 and 23, 12 is the maximum.
  3. Among 1 and -1, 1 is the maximum.

Min()

Min() will return the minimum number from the given two numbers.

Syntax:

math.Min(a,b)

min function accepts two variables as a parameter for comparison and let the two numbers be an a and b. Cases:

If a or b is negative Infinity, then the result is negative infinity (-Inf).

If a or b is NaN, then the result is NaN.

Min() Examples:-

To use the Min function also, its required to import the "math" package.

The following examples will demonstrate the above use cases.

Example 1:

Output:

CopiedCopy Code

-Inf
-Inf
NaN
NaN

Example 2:

CopiedCopy Code

package main

import (
	"fmt"
	"math"
)

func main() {

// let a = 12, b=23
fmt.Println(math.Min(12,23))

// let a = 12, b=3
fmt.Println(math.Min(12,3))

// let a = 1, b=-1
fmt.Println(math.Min(1,-1))

}

Output:

CopiedCopy Code

12
3
-1

Explanation of the above examples output.

  1. Among 12 and 23, 12 is the minimum.
  2. Among 12 and 23, 3 is the minimum.
  3. Among 1 and -1, -1 is the minimum.

Conclusion

Now we know how to find a max and min numbers in a Golang using Min() and Max() functions and understood the implementation with working examples.