Go Operators
Go provides arithmetic, comparison, and logical operators that let you compute values and build the conditions your programs branch on.
Arithmetic Operators
Go supports the standard arithmetic operators: + for addition, - for subtraction, * for multiplication, / for division, and % for the remainder (modulo). Division between two integers truncates toward zero rather than rounding, which is a common source of confusion for newcomers — 5 / 2 is 2, not 2.5.
Arithmetic Basics
package main
import "fmt"
func main() {
a, b := 17, 5
fmt.Println("Sum:", a+b)
fmt.Println("Difference:", a-b)
fmt.Println("Product:", a*b)
fmt.Println("Quotient:", a/b)
fmt.Println("Remainder:", a%b)
}Comparison Operators
Comparison operators — ==, !=, <, >, <=, >= — compare two values of the same type and always produce a bool. These are the building blocks of if statements, for loop conditions, and switch cases. Go does not allow comparing values of different types directly; you must convert one side first.
Comparing Values
package main
import "fmt"
func main() {
age := 20
votingAge := 18
fmt.Println("Equal:", age == votingAge)
fmt.Println("Not equal:", age != votingAge)
fmt.Println("Can vote:", age >= votingAge)
fmt.Println("Younger:", age < votingAge)
}Logical Operators
Logical operators combine or invert boolean values: && (AND) is true only when both operands are true, || (OR) is true when at least one operand is true, and ! (NOT) flips a boolean's value. Go uses short-circuit evaluation, meaning the right-hand side of && or || is only evaluated if it is actually needed.
Combining Conditions
package main
import "fmt"
func main() {
age := 25
hasLicense := true
isSuspended := false
canDrive := age >= 18 && hasLicense && !isSuspended
fmt.Println("Can drive:", canDrive)
isWeekend := true
isHoliday := false
isDayOff := isWeekend || isHoliday
fmt.Println("Day off:", isDayOff)
}- Arithmetic: +, -, *, /, % (remainder)
- Comparison: ==, !=, <, >, <=, >= — always return bool
- Logical: && (and), || (or), ! (not) — short-circuit evaluated
- Assignment shorthands: +=, -=, *=, /=, ++ and -- also exist for updating variables in place
Exercise: Go Operators
How does Go handle integer division, such as 7 / 2?