Addition Operator in Go

Golang Addition Operator takes two operands and returns the addition of these two operands. Both the operands provided to Addition Operator should be of same datatype.

Golang Addition Operator applies to integers, floats, complex values, and string of course. Since we are discussing about Arithmetic operations, string is excluded in this tutorial.

Addition Operator is also called Sum Operator.

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

Syntax

The syntax to add two operands a and b, 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

Add Integers

In the following example, we take two integer values and add them using addition operator.

Example.go

</>
Copy
package main

func main() {
	a := 4
	b := 3
	result := a + b
	println("Addition (a+b) = ", result)
}

Output

Addition (a+b) =  7

Add Floating Point Values

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

Example.go

</>
Copy
package main

func main() {
	a := 4.1
	b := 3.2
	result := a + b
	println("Addition (a+b) = ", result)
}

Output

Addition (a+b) =  +7.300000e+000

Add Complex Numbers

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

Example.go

</>
Copy
package main

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

Output

Addition (a+b) =  (+7.000000e+000+4.000000e+000i)

Add Float and Integer

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

Example.go

</>
Copy
package main

func main() {
	a := 3.14
	b := 5
	result := a + b
	println("Addition (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 Addition Operator in Go language, with the syntax and example programs.