What is the Abs function in golang?

Share

The Abs function in the Go programming language is used to find the absolute value of any given number.

Given a positive number, it is returned unchanged, while if a negative number is given as input to the Abs function, the number’s positive equivalent is returned.

To use this function, you must import the math package in your file and access the Abs function within it using the . notation (math.Abs). Here, Abs is the actual function, while math is the Go package that stores the definition of this function.

Function definition

The definition of the Abs function inside the math package is:

Parameters

The Abs function takes a single argument of type float64 and is the number you want to find the absolute value of.

Return value

The Abs function returns a single value of type float64. This value represents the absolute value of the given argument. So, all returned values are greater or equal to 0.

The above statement has the following two types of arguments that are given to it:

  • Infinity: Upon sending either positive or negative infinity as an argument to the Abs function, it returns positive infinity.

  • NAN: Upon sending a non-numeric argument the Abs function returns NAN.

Examples

The following is a simple example in which we find out the value of 25:

package main
import ("fmt"
"math")
func main() {
x := -25.0
y := math.Abs(x)
fmt.Print(y)
}

Although passing an integer variable as an argument to the Abs function results in an error, if you directly pass an integer value to it, the value gets automatically typecasted into a float64, and the function works as intended, as displayed by the following example:

package main
import ("fmt"
"math")
func main() {
y := math.Abs(math.Inf(1))
fmt.Print(y)
}
Copyright ©2024 Educative, Inc. All rights reserved