Operators

An operator is a symbol that works with values, like + or <. This lesson covers the operators that calculate and the ones that compare.

Arithmetic operators

package main

import "fmt"

func main() {
	a := 7
	b := 2
	fmt.Println(a + b)
	fmt.Println(a - b)
	fmt.Println(a * b)
	fmt.Println(a / b)
	fmt.Println(a % b)
}

Output:

9
5
14
3
1

Look at the fourth line: 7 / 2 gave 3, not 3.5. When both values are integers, Go does integer division. It keeps only the whole part of the answer and drops the rest. It does not round: the real answer 3.5 became 3, not 4.

The last operator, %, is called modulo. It gives the remainder of a division. 7 divided by 2 is 3, with 1 left over, so 7 % 2 is 1. Together, / and % can take a number apart. With 10, they give the last digit and the digits before it:

n := 472
fmt.Println(n % 10)
fmt.Println(n / 10)

Output:

2
47

You will use this trick often in coding problems about digits. % 2 is just as common: a number is even when n % 2 is 0.

If at least one value has a decimal part, the division keeps it:

fmt.Println(7.0 / 2)

Output:

3.5

As in math, *, / and % happen before + and -. Use parentheses to change the order:

fmt.Println(2 + 3*4)
fmt.Println((2 + 3) * 4)

Output:

14
20

+ also joins two strings: "Go" + "pher" is "Gopher".

int and float64 do not mix

Go will not calculate with an int and a float64 together:

package main

import "fmt"

func main() {
	minutes := 90
	rate := 1.5
	fmt.Println(minutes * rate)
}

Output:

# command-line-arguments
./main.go:8:14: invalid operation: minutes * rate (mismatched types int and float64)

"Mismatched types" means the two sides have different types. You have to turn one of them into the other type first. The Type Conversion lesson shows how.

Shortcuts

x += 5 is short for x = x + 5. There are also -=, *=, /= and %=. x++ adds 1 to x, and x-- takes 1 away:

x := 10
x += 5
x *= 2
x++
fmt.Println(x)

Output:

31

x started at 10. Adding 5 made it 15, doubling made it 30, and x++ made it 31.

In Go, x++ is a statement on its own line. It does not give back a value, so you cannot use it inside another line:

package main

import "fmt"

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

Output:

# command-line-arguments
./main.go:7:8: syntax error: unexpected ++ at end of statement

Write x++ on its own line, and use x after it.

Comparison operators

A comparison asks a question, and the answer is a bool. The operators are == (equal), != (not equal), >, <, >= and <=:

a := 7
b := 2
fmt.Println(a > b)
fmt.Println(a == b)
fmt.Println(a != b)

Output:

true
false
true

Be careful: "equal" is two equals signs, ==. A single = is assignment. To combine two comparisons, you need the logical operators, which come in the Logical Operators lesson.

In the exercise, turn a number of minutes into hours and minutes with / and %.