What is the imag function in Golang?

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 main
import (
"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 1010 and 1111 initializes a complex object based on the values provided for the real and imaginary parts.

The imag function in lines 1414 and 1515 proceeds to extract the imaginary part of each complex object, i.e., 22 and 44, respectively. The extracted imaginary values are then output.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved