SyntaxPilot
Courses/Go Programming/Lesson 6

Go Programming · Lesson 6 of 89 · 11 min

Operators and expressions

arithmetic operatorsinteger division and modulo with negativescomparison operatorslogical operators and short-circuitbitwise AND (&)ORXOR (^)AND NOT (&^)shifts << and >>unary ^ (bitwise NOT)operator precedenceassignment operators++ and -- as statements not expressions

These are the notes for Go episode 6. You will learn every operator Go has: arithmetic, integer division and the remainder (modulo), and why -3 % 2 is -1; what happens when you divide by zero (a compile error, a panic, or +Inf); comparisons; the logical operators &&, || and ! with short-circuit evaluation; the bitwise operators &, |, ^, &^, the shifts << and >> and bitwise NOT; operator precedence (with one Go surprise); the assignment operators like +=; and why x++ is a statement in Go, not a value. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).

First, two words used all the way through:

  • An operator is a symbol that does something to values, like + or ==. The values it works on are its operands: in 10 + 3, the operands are 10 and 3.
  • An expression is any piece of code that produces a value: 10 + 3, age >= 18, or just price. A statement is a complete instruction that does something, like x := 5 or fmt.Println(x). Keep this difference in mind; it matters at the end.

The problem: share 10 laddoos among 3 kids

Ten laddoos, three kids, share them fairly. You can't break a laddoo, so everyone gets whole ones. Each kid gets three, and one is left over for the cook. Two different answers from one sharing: how many each, and how many left. Let's ask Go.

package main

import "fmt"

func main() {
    laddoos := 10
    kids := 3
    fmt.Println(laddoos+kids, laddoos-kids, laddoos*kids)
    fmt.Println("each:", laddoos/kids)
    fmt.Println("left over:", laddoos%kids)
    fmt.Println(10.0 / 3)
}
13 7 30
each: 3
left over: 1
3.3333333333333335

These are the arithmetic operators:

Operator Meaning Example Result
+ add 10 + 3 13
- subtract 10 - 3 7
* multiply 10 * 3 30
/ divide 10 / 3 3 (both ints)
% remainder (modulo) 10 % 3 1
  • When both sides are ints, / does integer division: it gives the whole part and drops the rest.
  • % gives the remainder, the leftover: 1. This operator is called modulo (or "mod").
  • With a float, 10.0 / 3 gives 3.3333333333333335, the real answer (with float's tiny rounding error from episode 4). The types decide which division you get.

The next problem: is -3 odd?

A very common job: checking whether a number is odd. Say a parking app lets odd number plates in on odd days. The obvious check: divide by two, and if one is left over, it's odd: n % 2 == 1. It works for 3, 5 and 7. Now try minus three.

package main

import "fmt"

func main() {
    n := -3
    fmt.Println("is -3 odd?", n%2 == 1)
    fmt.Println(-3%2, -7/2, -7%2, 7%-2)
}
is -3 odd? false
-1 -3 -1 1

False! Minus three is odd, but the check says no. Look at the second line: -3 % 2 is -1, not 1. No error, just a wrong answer.

Why: Go's division chops toward zero

  • Go's integer division always chops toward zero. -7 / 2 is -3.5, chopped to -3 (not -4). Chopping off the decimal part like this is called truncation.
  • The remainder then takes the sign of the number being divided (the left one): -7 % 2 is -1, and 7 % -2 is +1.
a == (a/b)*b + a%b      // always true
-7 / 2 = -3     -7 % 2 = -1

Here's the rule Go guarantees: a equals a / b, times b, plus the remainder. Check: -3 × 2 is -6, plus -1 is -7. Correct. Truncation forces the remainder to have the same sign as a.

The fix: n % 2 != 0

So the safe odd check is: n modulo 2 is not equal to 0. != ("not equals", written exclamation mark, equals) is true for 3 and for -3, because their remainders (1 and -1) are both not zero.

package main

import "fmt"

func main() {
    n := -3
    fmt.Println("is -3 odd?", n%2 != 0)
    fmt.Println("is 7 odd?", 7%2 != 0)
}
is -3 odd? true
is 7 odd? true

Correct for every number.

Dividing by zero: three different outcomes

Now share a bill among zero friends. First, ten divided by zero, written directly:

package main

import "fmt"

func main() {
    fmt.Println(10 / 0)
}
./main.go:6:22: invalid operation: division by zero

Both numbers are constants (fixed values Go can see while compiling, episode 5), so Go catches it while compiling, before the program runs.

Now with variables: a Rs 600 bill, and friends is 0.

package main

import "fmt"

func main() {
    bill := 600
    friends := 0
    fmt.Println(bill / friends)
}
panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.main()
    main.go:8 +0x9
exit status 2
  • A panic is Go stopping the program because something impossible happened while it was running (a runtime error).
  • It tells you where: main.main(), the main function in package main, file main.go, line 8. (A goroutine is a running line of work in Go; goroutine 1 is your main program. Goroutines get their own episodes later.)
  • exit status 2 means the program ended with an error code (2) instead of finishing normally (0).

Floats behave differently:

package main

import "fmt"

func main() {
    zero := 0.0
    fmt.Println(600/zero, -600/zero)
}
+Inf -Inf

+Inf and -Inf are plus and minus infinity, special float values meaning "bigger (or smaller) than any number". No crash, but a value you probably didn't want.

Divide by zero What happens
a constant zero: 10 / 0 compile error: invalid operation: division by zero
an integer variable that is 0 panic while running: integer divide by zero
a float variable that is 0 no crash: +Inf or -Inf

Either way: check for zero before you divide.

Comparisons and logic: the bouncer at the gate

Comparison operators compare two values and give a bool (true or false):

Operator Meaning
== equal to
!= not equal to
< / > less than / greater than
<= / >= less than or equal / greater than or equal

To combine bools, think of the bouncer at the fest gate:

At the fest gate In Go
Ticket AND ID card: both, or you don't enter && (AND): true only if both are true
Member OR guest: either one is enough || (OR): true if at least one is true
NOT on the banned list: flips the answer ! (NOT): true becomes false, false becomes true

These three are the logical operators. AND is two ampersands, OR is two vertical bars, NOT is an exclamation mark.

package main

import "fmt"

func main() {
    age := 20
    fmt.Println(age == 18, age != 18, age < 18, age >= 18)
    hasTicket := true
    hasID := false
    fmt.Println(hasTicket && hasID, hasTicket || hasID, !hasID)
}
false true false true
false true true

Twenty is not 18, is not less than 18, is at least 18. Ticket and ID: false. Ticket or ID: true. Not hasID: true.

Logical operators work only on bools. a && b with two ints fails: invalid operation: operator && not defined on a (variable of type int).

Short-circuit: the bouncer stops early

If you have no ticket, the bouncer doesn't bother checking your ID.

  • a && b: if a is false, b is never checked (the answer is already false).
  • a || b: if a is true, b is never checked (the answer is already true).

This is called short-circuit evaluation. It lets you guard a dangerous check: first make sure friends isn't zero, and only then divide. Let's prove it. The wrong order first: divide first, check friends second.

package main

import "fmt"

func main() {
    bill := 600
    friends := 0
    fmt.Println(bill/friends > 100 && friends != 0)
}
panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.main()
    main.go:8 +0x9
exit status 2

The division ran before the check. Swap them:

package main

import "fmt"

func main() {
    bill := 600
    friends := 0
    fmt.Println(friends != 0 && bill/friends > 100)
}
false

False, and no crash. The left side was false, so the division was never done. Put the guard on the left.

Bitwise operators: operators on the switches

In episode 4, a number's bits were light switches (each 0 or 1), and in episode 5 we used one & and one | on them. These operators work bit by bit, so they're called bitwise operators.

1100 & 1010 = 1000   AND: on in both
1100 | 1010 = 1110   OR: on in either
1100 ^ 1010 = 0110   XOR: on in exactly one
1100 &^ 1010 = 0100  AND NOT: switch off b's bits

1 << 3 = 8     40 >> 2 = 10     ^x flips every bit
Operator Name A result bit is 1 when ...
& bitwise AND it's on in both numbers
| bitwise OR it's on in either number
^ (between two values) XOR, exclusive or it's on in exactly one, not both
&^ AND NOT (bit clear) it's on in a and off in b: it switches off every bit that's on in b, like removing toppings from an order
<< shift left moves all bits left; each step doubles (1 << 3 = 8)
>> shift right moves all bits right; each step halves (40 >> 2 = 10)
^x (in front of one value) unary ^, bitwise NOT every bit flips

(Unary means the operator has just one operand. Binary operator in this sense means two operands, like a ^ b.)

0b at the start of a number means it's written in binary: 0b1100 is 12 and 0b1010 is 10. This is a binary literal. (A literal is a value written directly in code.)

package main

import "fmt"

func main() {
    a, b := 0b1100, 0b1010
    fmt.Printf("a &  b = %04b\n", a&b)
    fmt.Printf("a |  b = %04b\n", a|b)
    fmt.Printf("a ^  b = %04b\n", a^b)
    fmt.Printf("a &^ b = %04b\n", a&^b)
    fmt.Println(1<<3, 40>>2, ^5)
}
a &  b = 1000
a |  b = 1110
a ^  b = 0110
a &^ b = 0100
8 10 -6
  • %04b prints a number in binary, padded to 4 digits (episode 5).
  • 1000, 1110, 0110, 0100, exactly as on the notepad. 1 << 3 is 8, 40 >> 2 is 10.
  • But ^5 is -6? For a signed int, flipping every bit also flips the sign bit (the leftmost bit, which marks negatives, episode 4), and that pattern means -6. (In general, ^x is -x - 1 for signed ints.)

On an unsigned uint8, it's easier to see:

package main

import "fmt"

func main() {
    var x uint8 = 0b00001111
    fmt.Printf("%08b\n", ^x)
    fmt.Println(^x)
}
11110000
240

00001111 became 11110000: 240. Every switch flipped.

Watch out: ^ is not "power of". fmt.Println(2 ^ 3) prints 1 (10 XOR 11 = 01), not 8. Use 1 << 3 for powers of two, or math.Pow for floats.

Precedence: who goes first?

When an expression mixes operators, which goes first? Like school maths, multiplication before addition. Go has exactly five levels. This order is called operator precedence.

Level Operators
5 (first) * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 (last) ||
  • On top: multiply, divide, modulo, the shifts, and the AND operators. Then the adding kind: plus, minus, OR, XOR. Then the comparisons. Then &&. And last, ||.
  • Operators on the same level go left to right (this is called left-to-right associativity).
  • Brackets ( ) always go first. Not sure? Add brackets.
package main

import "fmt"

func main() {
    fmt.Println(2+3*4, (2+3)*4)
    fmt.Println(1<<2 + 1)
    fmt.Println(10-4-3, 100/10/5)
}
14 20
5
3 2
  • 2+3*4 is 14; with brackets, (2+3)*4 is 20.
  • Go's surprise: 1<<2 + 1 is 5. In Go, shift is on the multiply level, so it goes before plus: (1<<2) + 1 = 4 + 1. In C or Java that same line gives 8, because there + goes first: 1 << 3.
  • 10-4-3 is (10-4)-3 = 3, and 100/10/5 is (100/10)/5 = 2: left to right.

Assignment operators: += and friends

Updating a variable from itself is so common that it has a shortcut. score += 5 means score = score + 5. Same for *=, -=, /= and %=. The comments show each step:

package main

import "fmt"

func main() {
    score := 10
    score += 5  // 15
    score *= 2  // 30
    score -= 6  // 24
    score /= 4  // 6
    score %= 4  // 2
    fmt.Println(score)
}
2

Two, as the comments said: 10 → 15 → 30 → 24 → 6 → 2. These are the assignment operators, and there's one for every arithmetic and bitwise operator (+= -= *= /= %= &= |= ^= <<= >>= &^=).

++ and -- are statements, not expressions

x++ adds one, x-- subtracts one (the increment and decrement statements). In C or Java you can write y = x++. Try it in Go:

package main

import "fmt"

func main() {
    x := 5
    y := x++
    fmt.Println(x, y)
}
./main.go:7:11: syntax error: unexpected ++ at end of statement
  • A syntax error means the code breaks Go's grammar rules, so it can't even be read.
  • In Go, x++ is a statement, a complete instruction on its own line. It's not an expression, so it has no value you can store.
  • And there's no ++x at all: writing ++x gives syntax error: unexpected ++, expected }.

The Go way: x++ on its own line, then use x.

package main

import "fmt"

func main() {
    x := 5
    x++
    y := x
    fmt.Println(x, y)
}
6 6

Go removed the tricky question of whether you get the value before or after adding one.

Common mistakes (and the real error messages)

You wrote Real error Fix
n%2 == 1 for n = -3 no error: false (-3 % 2 is -1) n%2 != 0
fmt.Println(10 / 0) invalid operation: division by zero never divide by a zero constant
bill / friends with friends = 0 panic: runtime error: integer divide by zero friends != 0 && ...
600 / zero (float zero) no error: +Inf check for zero first
bill/friends > 100 && friends != 0 panic: runtime error: integer divide by zero put the guard on the left
y := x++ syntax error: unexpected ++ at end of statement x++ then y := x
++x syntax error: unexpected ++, expected } x++
a && b with ints invalid operation: operator && not defined on a (variable of type int) compare first: a != 0 && b != 0
price % 2 with a float64 invalid operation: operator % not defined on price (variable of type float64) % is for integers; use math.Mod for floats
2 ^ 3 for "2 cubed" no error: prints 1 (XOR) 1 << 3, or math.Pow(2, 3)
1<<2 + 1 expecting 8 no error: prints 5 1 << (2 + 1)

Mini project: a movie's running time

A movie runs for 9876 seconds. How long is that in hours, minutes and seconds?

  • Hours: integer division by 3600, the seconds in an hour.
  • Minutes: the remainder after taking out the hours, divided by 60. Precedence says % and / are on one level, so they go left to right: (total % 3600) / 60.
  • Seconds: the remainder after dividing by 60.
package main

import "fmt"

func main() {
    // Mini project: a movie's running time
    total := 9876 // seconds
    hours := total / 3600
    minutes := total % 3600 / 60
    seconds := total % 60
    fmt.Printf("%dh %dm %ds\n", hours, minutes, seconds)
}
2h 44m 36s

Two hours, 44 minutes, 36 seconds. Division and modulo together turn one big number into its parts.

Extension: a clock-style display, with a check

package main

import "fmt"

func main() {
    // Extension: a clock-style display
    total := 9876 // seconds
    hours := total / 3600
    minutes := total % 3600 / 60
    seconds := total % 60
    fmt.Printf("%02d:%02d:%02d\n", hours, minutes, seconds)
    fmt.Println("check:", hours*3600+minutes*60+seconds)
}
02:44:36
check: 9876

%02d prints an integer at least 2 digits wide, padded with a leading zero. The check line puts the parts back together and gets the original 9876, so nothing was lost.

Practice

  1. Check whether 2026 is divisible by 4.
  2. Print 17 / 5, 17 % 5, -17 / 5 and -17 % 5. Predict first.
  3. Guard a division with a short-circuit check, for 0 friends and for 4 friends.
  4. Convert 100000 seconds into days, hours, minutes and seconds.
Solutions and hints
  1. "Divisible" means the remainder is 0:
package main

import "fmt"

func main() {
    year := 2026
    fmt.Println(year, "% 4 =", year%4)
    fmt.Println("divisible by 4?", year%4 == 0)
    fmt.Println("2028 divisible by 4?", 2028%4 == 0)
}
2026 % 4 = 2
divisible by 4? false
2028 divisible by 4? true
  1. fmt.Println(17/5, 17%5, -17/5, -17%5) prints 3 2 -3 -2. -3.4 chops toward zero to -3; then -3 × 5 = -15, and -17 - (-15) = -2, with the sign of -17.

  2. The guard goes on the left:

package main

import "fmt"

func main() {
    bill := 600
    friends := 0
    fmt.Println("can split?", friends != 0 && bill/friends > 0)
    friends = 4
    fmt.Println("can split?", friends != 0 && bill/friends > 0)
    fmt.Println("each pays:", bill/friends)
}
can split? false
can split? true
each pays: 150
  1. A day has 24 × 3600 = 86400 seconds:
package main

import "fmt"

func main() {
    total := 100000
    days := total / 86400
    hours := total % 86400 / 3600
    minutes := total % 3600 / 60
    seconds := total % 60
    fmt.Printf("%dd %dh %dm %ds\n", days, hours, minutes, seconds)
}
1d 3h 46m 40s

Quick quiz

What does this print (inside main)?

fmt.Println(-7 % 3)
  • A. 2
  • B. -1
  • C. 1
  • D. -2
Answer

B. -1. -7 / 3 = -2.33, chopped toward zero to -2. -2 × 3 = -6, and -7 - (-6) = -1. The remainder has the sign of -7, the left number.

Interview questions

  • What does integer division do in Go? What is -7 / 2?
  • What sign does the result of % have in Go? Why does n % 2 == 1 fail for negative numbers?
  • What happens when you divide by zero: with constants, with integer variables, with floats?
  • What is short-circuit evaluation? Show how it prevents a crash.
  • Explain &, |, ^, &^, <<, >> and unary ^. What is ^5 and why?
  • What is 1<<2 + 1 in Go, and why is it different in C or Java?
  • Why can't you write y := x++ in Go? Is there a ++x?
  • How many precedence levels does Go have? Which operators are on the top level?
  • What is the difference between a statement and an expression?

Glossary

Term Meaning Example
Operator a symbol that does something to values +, ==, &&
Operand a value an operator works on 10 and 3 in 10 + 3
Expression code that produces a value age >= 18
Statement a complete instruction that does something; has no value x++, x := 5
Arithmetic operators + - * / %: add, subtract, multiply, divide, remainder laddoos*kids
Integer division / with two ints: keeps the whole part, drops the rest 10 / 3 = 3
Modulo % the remainder after integer division 10 % 3 = 1
Truncation chopping off the decimal part, toward zero -7 / 2 = -3
Toward zero rounding a result in the direction of 0 (up for negatives, down for positives) -3.5 → -3
Remainder sign rule in Go, a % b has the sign of a -7 % 2 = -1, 7 % -2 = 1
Odd check n % 2 != 0 works for negatives too -3 % 2 != 0 is true
Division by zero (constant) caught while compiling invalid operation: division by zero
Panic Go stopping the program because something impossible happened while running integer divide by zero
Runtime error an error that happens while the program runs, not while compiling the panic above
Goroutine a running line of work in Go; goroutine 1 is your main program goroutine 1 [running]
Exit status the code a program ends with: 0 = OK, non-zero = error exit status 2
+Inf / -Inf float infinity, from dividing a float by zero 600/zero
Comparison operators == != < <= > >=; each gives a bool age >= 18
bool a value that is only true or false hasID := false
Logical operators && (AND), || (OR), ! (NOT); work on bools hasTicket && hasID
&& (AND) true only if both sides are true true && false = false
|| (OR) true if at least one side is true true || false = true
! (NOT) flips a bool !false = true
Short-circuit evaluation && skips the right side if the left is false; || skips it if the left is true friends != 0 && bill/friends > 100
Guard a safe check placed first so a dangerous one never runs friends != 0
Bit one binary on/off switch, 0 or 1
Sign bit leftmost bit of a signed integer; 1 means negative why ^5 = -6
Binary literal a number written in binary with 0b 0b1100 = 12
Literal a value written directly in code 600, "hi", 0b1010
Bitwise operators operators that work on each bit separately a & b
Bitwise AND & 1 where both bits are 1 1100 & 1010 = 1000
Bitwise OR | 1 where either bit is 1 1100 | 1010 = 1110
XOR ^ exclusive or: 1 where exactly one bit is 1 1100 ^ 1010 = 0110
AND NOT &^ bit clear: switches off every bit that is on in the right side 1100 &^ 1010 = 0100
Shift left << moves bits left; each step doubles 1 << 3 = 8
Shift right >> moves bits right; each step halves 40 >> 2 = 10
Unary operator an operator with one operand ^x, !ok, -n
Unary ^ (bitwise NOT) flips every bit of one value ^uint8(15) = 240
%b / %04b / %08b Printf: binary, padded to 4 / 8 digits %08b → 11110000
%d / %02d Printf: integer / integer padded to 2 digits with a zero %02d of 2 → 02
Operator precedence the order in which mixed operators are worked out; Go has 5 levels 2+3*4 = 14
Left-to-right associativity operators on the same level are done left to right 10-4-3 = 3
Brackets ( ) force part of an expression to go first (2+3)*4 = 20
Assignment operators += -= *= /= %= and bitwise ones: update a variable from itself score += 5
++ / -- add one / subtract one; statements, not expressions x++
Increment / decrement adding one / subtracting one x++, x--
Syntax error code that breaks Go's grammar rules unexpected ++ at end of statement
math.Mod / math.Pow float remainder / power, from the math package math.Pow(2, 3) = 8

Summary

  • Arithmetic: + - * / %. int / int chops toward zero (truncation); % is the remainder.
  • The remainder has the sign of the left number: -3 % 2 is -1, so check odd with n % 2 != 0.
  • Zero divisors: a constant gives a compile error, an int variable a panic, a float +Inf/-Inf. Check for zero first.
  • Comparisons give bools; &&, ||, ! combine them; short-circuit lets a guard go first.
  • Bitwise & | ^ &^, shifts << >>, and unary ^x flips every bit (^5 is -6 for a signed int).
  • Five precedence levels; shifts are on the multiply level, so 1<<2 + 1 is 5. Use brackets when unsure.
  • += and friends are shortcuts. x++ is a statement, not a value: no y := x++, no ++x.

Next episode: control flow with if and switch. So far our programs only print true or false. Next, a cinema ticket that costs less for children and seniors, and your programs start making decisions with if and switch.