Introduction
Arithmetic operators are used to perform basic mathematical operations. In Go, these operators allow you to add, subtract, multiply, divide, and find the remainder of numeric values. In this chapter, you will learn different arithmetic operators in Go, with examples for each type.
Arithmetic Operators in Go
Addition (+)
The addition operator adds two operands.
Syntax:
result = operand1 + operand2
Example:
package main
import "fmt"
func main() {
var a int = 5
var b int = 3
var sum int = a + b
fmt.Println("Sum:", sum) // Output: Sum: 8
}
Subtraction (-)
The subtraction operator subtracts the right operand from the left operand.
Syntax:
result = operand1 - operand2
Example:
package main
import "fmt"
func main() {
var a int = 5
var b int = 3
var difference int = a - b
fmt.Println("Difference:", difference) // Output: Difference: 2
}
Multiplication (*)
The multiplication operator multiplies two operands.
Syntax:
result = operand1 * operand2
Example:
package main
import "fmt"
func main() {
var a int = 5
var b int = 3
var product int = a * b
fmt.Println("Product:", product) // Output: Product: 15
}
Division (/)
The division operator divides the left operand by the right operand.
Syntax:
result = operand1 / operand2
Example:
package main
import "fmt"
func main() {
var a int = 6
var b int = 3
var quotient int = a / b
fmt.Println("Quotient:", quotient) // Output: Quotient: 2
}
Modulus (%)
The modulus operator returns the remainder of the division of two operands.
Syntax:
result = operand1 % operand2
Example:
package main
import "fmt"
func main() {
var a int = 5
var b int = 3
var remainder int = a % b
fmt.Println("Remainder:", remainder) // Output: Remainder: 2
}
Combining Arithmetic Operators
You can use multiple arithmetic operators in a single expression to perform complex calculations.
Example:
package main
import "fmt"
func main() {
var a int = 10
var b int = 5
var c int = 2
var result int = (a + b) * c
fmt.Println("Result:", result) // Output: Result: 30
}
Using Arithmetic Operators with Different Types
Go requires that operands be of the same type. If you try to use arithmetic operators with different types, you will get a compile-time error. You need to explicitly convert one operand to the type of the other before performing the operation.
Example:
package main
import "fmt"
func main() {
var a int = 5
var b float64 = 3.2
// Convert int to float64
var sum float64 = float64(a) + b
fmt.Println("Sum:", sum) // Output: Sum: 8.2
}
Conclusion
Arithmetic operators in Go are essential for performing basic mathematical operations. Understanding how to use these operators allows you to perform calculations and manipulate numeric data effectively. By mastering addition, subtraction, multiplication, division, and modulus operators, you can handle a wide range of mathematical tasks in your Go programs.