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.
  • a and b are 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:

  1. Arithmetic operators: + - * / %.
  2. ++ and --.
  3. Relational operators: == != > < >= <=.
  4. Logical operators: && || !.
  5. Assignment operators like +=.
  6. Bitwise operators: & | ^ &^ << >>.
  7. Which operator runs first (precedence).

Arithmetic Operators

OperatorNameExampleResult
+add7 + 310
-subtract7 - 34
*multiply7 * 321
/divide7 / 32
%remainder7 % 31

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 / int drops the decimal part: 253 / 3 is 84.
  • Convert to float64 to keep decimals. See Data Types.
  • + also joins strings: "Go" + "pher" is "Gopher".

The Remainder Operator %

Remainder = what is left after dividing.

  • 17 % 5 is 2, 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 go tool, 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 to x.
  • x-- takes 1 from x.

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 write y := x++.
  • There is no ++x in Go. Only x++.

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, then next := 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.

OperatorMeansExampleResult
==equal to5 == 5true
!=not equal to5 != 3true
>greater than5 > 8false
<less than5 < 8true
>=greater than or equal35 >= 35true
<=less than or equal40 <= 35false

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.

OperatorNametrue when
&&ANDboth sides are true
||ORat least one side is true
!NOTthe 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, if a is false, Go never looks at b.
  • In a || b, if a is true, Go never looks at b.
  • 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 formSame as
x = 5put 5 in x
x += 3x = x + 3
x -= 3x = x - 3
x *= 3x = x * 3
x /= 3x = x / 3
x %= 3x = 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.

OperatorNameRule for each bit
&AND1 if both are 1
|OR1 if at least one is 1
^XOR1 if they are different
&^AND NOT (bit clear)keep a's bit, but clear it where b has 1
<<left shiftmove bits left: doubles each step
>>right shiftmove bits right: halves each step

Click the bits of a and b, then pick an operator.

Try these:

  • & with b = 1: shows if a is odd (last bit).
  • << by 1, 2, 3: a doubles each time.
  • &^: clears the bits of a that are on in b.

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
  • %08b prints 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
  • Read is 1, Write is 2, Delete is 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

OrderOperators
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/2 divides first: 40 + 40 = 80. That is a wrong average.
  • (unit + final) / 2 adds 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

  1. Arithmetic = + - * / %.

    • int / int drops decimals. % gives the remainder.
  2. Increment, decrement = x++, x--. Statements only, no ++x.
  3. Relational = == != > < >= <=. They give a bool.
  4. Logical = && (both), || (one), ! (flip).

    • Short-circuit = Go stops once it knows the answer.
  5. Assignment = = += -= *= /= %=.
  6. Bitwise = & | ^ &^ << >>. They work on bits.
  7. Precedence = multiply group, add group, compare, &&, ||.

    • Parentheses run first.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
if marks = 35= compares== compares, = assignsA build error.
253 / 3 for the exact average/ keeps decimalsConvert to float64 firstYou get 84, not 84.33....
next := count++++ gives a valuecount++ is its own statementA syntax error.
++countGo has prefix ++Only count++ existsA syntax error.
a + b / 2 for an averageGo goes left to right/ runs before +A wrong answer.
Dividing by a zero variableGo gives 0 or infinityIt is a panic for intsinteger divide by zero
2.5 % 2% works on floats% is for integers onlyA build error.

Check Yourself

Exercises

What to Remember

  • + - * / do maths. % gives the remainder. int / int drops decimals.
  • x++ and x-- are statements on their own line.
  • Comparisons give true or false. Use == to compare, not =.
  • && needs both, || needs one, ! flips.
  • x += 5 is short for x = 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.