Finding Minimum of Two Numbers in Golang


In Go, finding the minimum of two numbers is a straightforward process. In this article, we will discuss the different ways to find the minimum of two numbers in Go.

Using if-else Statement

One of the simplest ways to find the minimum of two numbers in Go is to use the if-else statement. Here's the code −

Example

package main

import "fmt"

func main() {
   a, b := 42, 24
   fmt.Printf("Min of %d and %d is %d\n", a, b, min(a, b))
}

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

Output

Min of 42 and 24 is 24

In this code, we are defining a function called min that takes two integer arguments a and b and returns the minimum of the two numbers. We are using the if-else statement to compare the two numbers and return the minimum value.

Using Ternary Operator

In Go, there is no built-in ternary operator like other programming languages. However, we can simulate it using the if-else statement. Here's the code −

Example

package main

import "fmt"

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

func main() {
   fmt.Println(min(5, 10)) // Output: 5
}

Output

5

In this code, we are defining a function called min that takes two integer arguments a and b and returns the minimum of the two numbers. We are using the if statement to compare the two numbers and return the minimum value.

Using math.Min Function

The math package in Go provides a Min function that can be used to find the minimum of two numbers. Here's the code −

Example

package main

import (
   "fmt"
   "math"
)

func main() {
   fmt.Println(min(5, 10))
   fmt.Println(min(15.5, 20.7))
}

func min(a, b interface{}) interface{} {
   switch a := a.(type) {
   case int:
      return int(math.Min(float64(a), float64(b.(int))))
   case float64:
      return math.Min(a, b.(float64))
   }
   return nil
}

Output

5
15.5

In this code, we create a main package, which is the package that Go expects for executable programs. We then import the fmt and math packages for printing and math functions, respectively.

We define a min function that takes two arguments of type interface{}, which allows us to accept any type of value. Inside the function, we use a type switch to determine the type of the arguments and then call the appropriate math.Min function.

In the main function, we call the min function twice with different types of arguments to demonstrate its flexibility.

Conclusion

In conclusion, there are different ways to find the minimum of two numbers in Go. You can use if-else statements, ternary operators, or the math package's Min function. It's important to choose the method that is most appropriate for your situation.

Updated on: 12-Apr-2023

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements