How to Use Arithmetic Operators in Go: Syntax and Examples
In Go, you use
+, -, *, /, and % to perform addition, subtraction, multiplication, division, and modulus operations respectively. These operators work with numeric types like int and float64 to calculate values in expressions.Syntax
Go supports basic arithmetic operators to perform calculations on numbers. Here are the main operators:
+: Adds two numbers.-: Subtracts the right number from the left.*: Multiplies two numbers./: Divides the left number by the right.%: Finds the remainder of integer division (modulus).
These operators can be used with variables or literals of numeric types like int and float64.
go
package main
func main() {
var a int = 10
var b int = 3
// Addition
c := a + b
// Subtraction
d := a - b
// Multiplication
e := a * b
// Division
f := a / b
// Modulus
g := a % b
_ = c
_ = d
_ = e
_ = f
_ = g
}Example
This example shows how to use arithmetic operators to calculate and print results for addition, subtraction, multiplication, division, and modulus.
go
package main import "fmt" func main() { a := 15 b := 4 fmt.Println("Addition:", a+b) // 19 fmt.Println("Subtraction:", a-b) // 11 fmt.Println("Multiplication:", a*b) // 60 fmt.Println("Division:", a/b) // 3 (integer division) fmt.Println("Modulus:", a%b) // 3 // Using float64 for division with decimals x := 15.0 y := 4.0 fmt.Println("Float Division:", x/y) // 3.75 }
Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3
Modulus: 3
Float Division: 3.75
Common Pitfalls
One common mistake is using integer division when you want a decimal result. Dividing two int values truncates the decimal part. To get a decimal result, use float64 values.
Another pitfall is using the modulus operator % with floating-point numbers, which is not allowed in Go.
go
package main import "fmt" func main() { // Wrong: integer division truncates decimals a := 7 b := 2 fmt.Println("Integer division:", a/b) // Outputs 3, not 3.5 // Right: convert to float64 for decimal division x := float64(a) y := float64(b) fmt.Println("Float division:", x/y) // Outputs 3.5 // Wrong: modulus with floats causes error // fmt.Println(7.5 % 2.0) // Compile error }
Output
Integer division: 3
Float division: 3.5
Quick Reference
| Operator | Description | Example |
|---|---|---|
| + | Addition | a + b |
| - | Subtraction | a - b |
| * | Multiplication | a * b |
| / | Division (integer or float) | a / b |
| % | Modulus (remainder of integer division) | a % b |
Key Takeaways
Use +, -, *, /, and % to perform arithmetic operations on numbers in Go.
Integer division truncates decimals; convert to float64 for precise division.
Modulus % works only with integers, not floats.
Always match operand types to avoid compile errors.
Use float64 for decimal calculations and int for whole numbers.