Subtraction Operator in Go

Golang Subtraction Operator takes two operands and the different of second operand from the first. Both the operands provided to Subtraction Operator should be of same datatype.

Golang Subtraction Operator applies to integers, floats, and complex values.

Subtraction Operator is also called Difference Operator.

In this tutorial, we will learn about the syntax to use Subtraction Operator, and some example scenarios on how to use Subtraction Operator.

Syntax

The syntax to find the difference of b from a, using Addition Operator is

</>
Copy
a-b

where a and b are operands and - is the operator symbol.

Return Value

The return value is of same datatype as that of first operand.

Examples

Subtract Integers

In the following example, we take two integer values and find their difference using Subtraction Operator.

Example.go

</>
Copy
package main

func main() {
	a := 7
	b := 3
	result := a - b
	println("Subtraction (a-b) = ", result)
}

Output

Subtraction (a-b) =  4

Subtract Floating Point Values

In the following example, we take two floating point numbers and find their difference using Subtraction Operator.

Example.go

</>
Copy
package main

func main() {
	a := 4.1
	b := 1.2
	result := a - b
	println("Subtraction (a-b) = ", result)
}

Output

Subtraction (a-b) =  +2.900000e+000

Subtract Complex Numbers

In the following example, we take two complex numbers and compute their difference. The real parts are subtracted, and the imaginary parts are subtracted separately.

Example.go

</>
Copy
package main

func main() {
	a := complex(2, 3)
	b := complex(5, 1)
	result := a - b
	println("Subtraction (a-b) = ", result)
}

Output

Subtraction (a-b) =  (-3.000000e+000+2.000000e+000i)

Subtract Integer from Float

In the following example, we take float value in first operand and integer value in second operand. We try to compute their difference using Subtraction Operator.

Example.go

</>
Copy
package main

func main() {
	a := 3.14
	b := 5
	result := a - b
	println("Subtraction (a-b) = ", result)
}

Output

./example.go:6:14: invalid operation: a - b (mismatched types float64 and int)

Conclusion

In this Golang Tutorial, we learned about Subtraction Operator in Go language, with the syntax and example programs.