Arithmetic operators help you do math with numbers in your program. They let you add, subtract, multiply, and divide values easily.
0
0
Arithmetic operators in Go
Introduction
Calculating the total price of items in a shopping cart.
Finding the difference between two dates or times.
Increasing a player's score in a game.
Splitting a bill evenly among friends.
Converting units, like inches to centimeters.
Syntax
Go
result := a + b // addition result := a - b // subtraction result := a * b // multiplication result := a / b // division result := a % b // remainder (modulus)
Use + to add, - to subtract, * to multiply, / to divide, and % to get the remainder.
Division between integers gives an integer result (no decimals). Use float types for decimal division.
Examples
Adds 5 and 3, then prints 8.
Go
sum := 5 + 3 fmt.Println(sum) // prints 8
Subtracts 4 from 10, then prints 6.
Go
diff := 10 - 4 fmt.Println(diff) // prints 6
Multiplies 7 by 6, then prints 42.
Go
product := 7 * 6 fmt.Println(product) // prints 42
Divides 20 by 3 giving 6 (integer division), and remainder 2.
Go
quotient := 20 / 3 fmt.Println(quotient) // prints 6 remainder := 20 % 3 fmt.Println(remainder) // prints 2
Sample Program
This program shows how to use all basic arithmetic operators with two numbers and prints the results.
Go
package main import "fmt" func main() { a := 15 b := 4 sum := a + b diff := a - b product := a * b quotient := a / b remainder := a % b fmt.Println("Sum:", sum) fmt.Println("Difference:", diff) fmt.Println("Product:", product) fmt.Println("Quotient:", quotient) fmt.Println("Remainder:", remainder) }
OutputSuccess
Important Notes
Remember that dividing two integers results in an integer. To get a decimal result, convert numbers to float64 first.
The modulus operator % only works with integers in Go.
Summary
Arithmetic operators let you do basic math in Go.
Use +, -, *, /, and % for addition, subtraction, multiplication, division, and remainder.
Integer division drops decimals; use floats for precise division.