Operators in Go
By Syncfusion®, Inc. · Last updated
Arithmetic, increment and decrement, relational, logical, assignment and bitwise operators in Go, and the order in which Go works out an expression.
What Are Operators?
Operator = a symbol that tells Go to do something with values.
Operand = a value the operator works on.
In a + b:
+is the operator.aandbare the operands.- The whole thing is an expression: something that gives a value.
Simple lesson: operators are the symbols Go uses to calculate, compare and decide.
A Real-World Example
The class teacher makes the report card.
- She adds the marks:
+ - She finds the average:
/ - She checks if the average is at least 35:
>= - She checks if attendance and marks are both good:
&&
Every one of these is an operator in Go.
Go has six groups of operators:
- arithmetic (maths)
- increment and decrement
- relational (compare)
- logical (combine true or false)
- assignment
- bitwise (work on the bits of a number)
What You Will Learn
In this lesson, you will learn:
- Arithmetic operators:
+ - * / %. ++and--.- Relational operators:
== != > < >= <=. - Logical operators:
&& || !. - Assignment operators like
+=. - Bitwise operators:
& | ^ &^ << >>. - Which operator runs first (precedence).
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | add | 7 + 3 | 10 |
- | subtract | 7 - 3 | 4 |
* | multiply | 7 * 3 | 21 |
/ | divide | 7 / 3 | 2 |
% | remainder | 7 % 3 | 1 |
Maths with marks
package main
import "fmt"
func main() {
maths, science, english := 91, 84, 78
total := maths + science + english
fmt.Println("Total:", total)
fmt.Println("Average:", total/3)
fmt.Println("Left over:", total%3)
fmt.Println("Exact average:", float64(total)/3)
}
Total: 253
Average: 84
Left over: 1
Exact average: 84.33333333333333
Division Needs Care
int / intdrops the decimal part:253 / 3is84.- Convert to
float64to keep decimals. See Data Types. +also joins strings:"Go" + "pher"is"Gopher".
The Remainder Operator %
Remainder = what is left after dividing.
17 % 5is2, because 17 = 5 × 3 + 2.%works only with integers.- A number is even when
n % 2 == 0.
Example: sharing 17 laddoos among 5 friends.
- Each friend gets
17 / 5= 3. 17 % 5= 2 laddoos are left over.
Dividing by Zero
Divide by zero
package main
import "fmt"
func main() {
marks := 90
students := 0
fmt.Println(marks / students)
}
- The program stops with
panic: runtime error: integer divide by zero. - Panic = Go stops the program because something went badly wrong.
- Always check that a number is not zero before dividing by it.
- In the real
gotool, the panic also shows the file and line number.
Go has no power operator like ** or ^ for maths.
^is bitwise XOR in Go, not "to the power of".- Use
math.Pow(2, 10)for 2 to the power 10. See Packages and Modules.
Simple lesson: + - * / do maths, % gives the remainder, and dividing ints drops the decimals.
Increment and Decrement
x++adds 1 tox.x--takes 1 fromx.
Count students in and out
package main
import "fmt"
func main() {
inRoom := 30
inRoom++
inRoom++
inRoom--
fmt.Println(inRoom)
}
31
Two Go Rules
x++is a statement, not an expression. You cannot writey := x++.- There is no
++xin Go. Onlyx++.
x++ is not an expression
package main
import "fmt"
func main() {
count := 5
next := count++
fmt.Println(next)
}
- Go stops with a syntax error at
count++. - Fix: write
count++on its own line, thennext := count.
Simple lesson: ++ adds one and -- takes one away, each on its own line.
Relational Operators
Relational operator = compares two values and gives a bool: true or false.
| Operator | Means | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5 | true |
!= | not equal to | 5 != 3 | true |
> | greater than | 5 > 8 | false |
< | less than | 5 < 8 | true |
>= | greater than or equal | 35 >= 35 | true |
<= | less than or equal | 40 <= 35 | false |
Compare marks
package main
import "fmt"
func main() {
marks := 35
passMark := 35
fmt.Println(marks >= passMark)
fmt.Println(marks > passMark)
fmt.Println(marks == passMark)
fmt.Println("Asha" == "asha")
}
true
false
true
false
=puts a value in a box.==asks "are these equal?".- Strings are compared letter by letter, and capital letters matter.
- Both sides must have the same type.
Simple lesson: relational operators compare two values and answer true or false.
Logical Operators
Logical operator = combines true and false answers.
| Operator | Name | true when |
|---|---|---|
&& | AND | both sides are true |
|| | OR | at least one side is true |
! | NOT | the value is false (it flips it) |
Flip the switches and watch the answers change.
Try every pair:
&&is true only when both switches are on.||is false only when both switches are off.!always gives the opposite.
Can the student enter the exam hall?
package main
import "fmt"
func main() {
hasHallTicket := true
attendance := 82
feesPaid := false
canEnter := hasHallTicket && attendance >= 75
needsReminder := !feesPaid || attendance < 75
fmt.Println(canEnter, needsReminder)
}
true true
Short-Circuit Evaluation
Short-circuit = Go stops checking as soon as it knows the answer.
- In
a && b, ifais false, Go never looks atb. - In
a || b, ifais true, Go never looks atb. - This lets you write safe checks like
count != 0 && total/count > 50.
Simple lesson: && needs both, || needs one, and ! flips the answer.
Assignment Operators
Assignment operator = changes a variable using its own value.
| Short form | Same as |
|---|---|
x = 5 | put 5 in x |
x += 3 | x = x + 3 |
x -= 3 | x = x - 3 |
x *= 3 | x = x * 3 |
x /= 3 | x = x / 3 |
x %= 3 | x = x % 3 |
Press Play and watch the wallet change.
Pocket money, step by step
- The short forms save typing.
- They also make clear that the variable changes itself.
Simple lesson: x += 5 is a short way to write x = x + 5.
Bitwise Operators
Every integer is stored as bits: 0s and 1s.
For example, 12 is 00001100 in 8 bits.
Bitwise operator = works on each bit of a number.
| Operator | Name | Rule for each bit |
|---|---|---|
& | AND | 1 if both are 1 |
| | OR | 1 if at least one is 1 |
^ | XOR | 1 if they are different |
&^ | AND NOT (bit clear) | keep a's bit, but clear it where b has 1 |
<< | left shift | move bits left: doubles each step |
>> | right shift | move bits right: halves each step |
Click the bits of a and b, then pick an operator.
Try these:
&with b = 1: shows ifais odd (last bit).<<by 1, 2, 3:adoubles each time.&^: clears the bits ofathat are on inb.
Bitwise operators
package main
import "fmt"
func main() {
a, b := 12, 10
fmt.Println(a&b, a|b, a^b, a&^b)
fmt.Println(a<<1, a>>2)
fmt.Printf("%08b\n", a)
}
8 14 6 4
24 3
00001100
%08bprints a number in binary, with 8 digits.- Shifts are a fast way to multiply or divide by 2, 4, 8 and so on.
A Practical Use: Permission Flags
Each bit can mean one permission, like a row of light switches.
Permissions as bits
package main
import "fmt"
const (
Read = 1 << iota
Write
Delete
)
func main() {
teacher := Read | Write
fmt.Println(teacher&Write != 0)
fmt.Println(teacher&Delete != 0)
teacher = teacher &^ Write
fmt.Println(teacher&Write != 0)
}
true
false
false
Readis 1,Writeis 2,Deleteis 4. Each uses its own bit.|turns permissions on.&checks one.&^turns one off.
Simple lesson: bitwise operators work on the 0s and 1s inside a number.
Operator Precedence
Precedence = which operator Go runs first.
It works like BODMAS in maths: * and / before + and -.
Evaluation Order
Press Play to see Go work out one expression.
How Go works out 2 + 3 * 4 > 10 && 6 % 4 == 2
| Order | Operators |
|---|---|
| 1 (first) | * / % << >> & &^ |
| 2 | + - | ^ |
| 3 | == != < <= > >= |
| 4 | && |
| 5 (last) | || |
- Inside one group, Go goes from left to right.
!and a minus sign on one value (like-x) run before everything else.
Parentheses
Parentheses ( ) = run this part first.
Parentheses change the answer
package main
import "fmt"
func main() {
fmt.Println(2 + 3*4)
fmt.Println((2 + 3) * 4)
unit, final := 40, 80
fmt.Println(unit + final/2)
fmt.Println((unit + final) / 2)
}
14
20
80
60
unit + final/2divides first: 40 + 40 = 80. That is a wrong average.(unit + final) / 2adds first: 120 / 2 = 60. That is the right average.
Easy way to remember
- Multiply before add, compare after maths,
&&before||. - When you are not sure, use parentheses. They also make code easier to read.
Simple lesson: Go runs * and / before + and -, and parentheses always run first.
TL;DR
Arithmetic =
+ - * / %.int / intdrops decimals.%gives the remainder.
- Increment, decrement =
x++,x--. Statements only, no++x. - Relational =
== != > < >= <=. They give abool. Logical =
&&(both),||(one),!(flip).- Short-circuit = Go stops once it knows the answer.
- Assignment =
= += -= *= /= %=. - Bitwise =
& | ^ &^ << >>. They work on bits. Precedence = multiply group, add group, compare,
&&,||.- Parentheses run first.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
if marks = 35 | = compares | == compares, = assigns | A build error. |
253 / 3 for the exact average | / keeps decimals | Convert to float64 first | You get 84, not 84.33.... |
next := count++ | ++ gives a value | count++ is its own statement | A syntax error. |
++count | Go has prefix ++ | Only count++ exists | A syntax error. |
a + b / 2 for an average | Go goes left to right | / runs before + | A wrong answer. |
| Dividing by a zero variable | Go gives 0 or infinity | It is a panic for ints | integer divide by zero |
2.5 % 2 | % works on floats | % is for integers only | A build error. |
Check Yourself
Exercises
What to Remember
+ - * /do maths.%gives the remainder.int / intdrops decimals.x++andx--are statements on their own line.- Comparisons give
trueorfalse. Use==to compare, not=. &&needs both,||needs one,!flips.x += 5is short forx = x + 5.- Bitwise operators work on bits:
& | ^ &^ << >>. *and/run before+and-. When unsure, use parentheses.
Next: Conditional Statements. You will learn how to make your program choose what to do with if, else and switch.