Calculating with operators
Go can do arithmetic on numbers and on variables that hold numbers. The five arithmetic operators are:
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 2 + 6 | 8 |
- | Subtraction | 10 - 7 | 3 |
* | Multiplication | 3 * 3 | 9 |
/ | Division | 6 / 2 | 3 |
% | Remainder (modulus) | 20 % 3 | 2 |
Each operator works on two values, called operands. An operand can be a plain number or a variable, because Go replaces the variable with its current value:
num := 6
fmt.Println(num + 5) // 11
fmt.Println(10 - num) // 4
fmt.Println(3 * num) // 18
fmt.Println(num / 2) // 3
This is the same arithmetic you know from school, written in code. Calculating with a variable doesn't change it. After those four lines, num is still 6. To store a result, assign it, with = or with a shorthand such as num += 5.
Integer division
Division is where Go surprises beginners. When both operands are integers, the result is an integer, and the fractional part is thrown away:
a := 2
b := 3
fmt.Println(20 / 3) // 6
fmt.Println(b / a) // 1
The result isn't rounded. It is truncated toward zero, so -7 / 2 is -3, not -4. The % operator gives the remainder that division leaves, and the two fit together: 20 / 3 is 6 and 20 % 3 is 2, since 6 * 3 + 2 is 20. The remainder takes the sign of the left operand, so -7 % 3 is -1. The operator % works only with integers.
Getting a decimal result
For a fractional result, the values need to be floating-point numbers. Literals with a decimal point are floats, and variables can be converted with float64(...):
fmt.Println(7.0 / 3.0) // 2.3333333333333335
fmt.Println(float64(b) / float64(a)) // 1.5
Go never mixes types in an expression on its own. A float64 variable times an int variable does not compile: Go reports mismatched types float64 and int. Convert one side so both have the same type.
Number literals adapt
Plain number literals are more flexible than variables. With b := 3, the expression float64(b) / 2 is fine and gives 1.5, because the literal 2 becomes a float64 to match. A literal can even look like a float if its value is whole: b * 2.0 compiles and gives 6. But b * 2.5 is rejected with 2.5 (untyped float constant) truncated to int, since an int can't hold the fraction. A variable never adapts like this, which is why conversions are needed between variables of different types.
Order of operations
Go follows the usual rules: *, / and % are done before + and -, and operators of the same level run from left to right. Parentheses override this. With price equal to 83:
fmt.Println(4 * price + 15) // 347
fmt.Println(4 * (price + 15)) // 392
The first line multiplies first (332) and then adds 15. The second adds first (98) and then multiplies.
Storing the result
A result can go straight into a variable. Each arithmetic operator has an assignment shorthand that updates a variable from its own value:
total := 10
total += 5 // same as total = total + 5
total *= 2 // same as total = total * 2
fmt.Println(total) // 30
The remainder operator is handy for checking divisibility. n % 2 == 0 is true when n is even, and n % 10 is the last digit of a non-negative number.
Dividing by zero
Dividing an integer variable by zero crashes the program at run time with integer divide by zero. Writing 5 / 0 with a literal zero is caught earlier, as a compile error. Floating-point division follows different rules and doesn't panic.
The exercise, step by step
The variable price holds the cost of one product, 83. Andy buys four of them and also a bag for 15. The task is to print the total.
- Multiply. Four products at
priceeach cost4 * price. - Add. The bag adds a flat 15, so the total is
4 * price + 15. - No parentheses. Multiplication already comes before addition, which is the order we want.
- Print. Put the expression directly in
fmt.Println.
var price int = 83
fmt.Println(4 * price + 15)
The output is 347.
Key takeaways
- The operators are
+,-,*,/and%. - Integer division drops the fraction;
%gives the remainder. - For decimal results, use floating-point values and convert with
float64(...). - Multiplication and division come before addition and subtraction.
- A calculation doesn't change its variables; assignment does.