Related Tags

golang

# What is the imag function in Golang?

Talha Ashar

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The imag function in Golang is a built-in function that extracts the imaginary part of a given complex number.

The process is illustrated below:

The prototype of the imag function is shown below:

func imag(c ComplexType) FloatType


## Parameters

The imag function takes a single mandatory parameter in the form of a ComplexType object.

## Return value

The imag function returns a FloatType object that represents the imaginary part of the complex number provided as a parameter.

If the given complex number is a complex64 object, then the imag function returns a float32 object. If the given complex number is a complex128 object, then the imag function returns a float64 object.

## Example

The code below shows how the imag function works in Golang:

package mainimport (	"fmt")func main() {  // initializing complex values	a := complex(15, 2)	b := complex (-5, 4)	  // extracting imaginary parts	fmt.Println("The imaginary part of", a , "is", imag(a))	fmt.Println("The imaginary part of", b , "is", imag(b))	}

## Explanation

The complex function in lines $10$ and $11$ initializes a complex object based on the values provided for the real and imaginary parts.

The imag function in lines $14$ and $15$ proceeds to extract the imaginary part of each complex object, i.e., $2$ and $4$, respectively. The extracted imaginary values are then output.

RELATED TAGS

golang

CONTRIBUTOR

Talha Ashar