TL ; DR:
When we string operations together, Go must know which one to do first. This is called operator precedence.
*,/, and%are performed before+and-:fmt.Println(1 + 2 * 3) // Prints 7 fmt.Println(6 - 4 / 2) // Prints 4 fmt.Println(5 * 4 - 2 / 2) // Prints 19We can add
()to force an operation to be performed first:fmt.Println((1 + 2) * 3) // Prints 9 fmt.Println((6 - 4) / 2) // Prints 1 fmt.Println(5 * (4 - 2) / 2) // Prints 5
Full lesson:
When we string operations together, Go must know which one to do first. This is called operator precedence.
This is the hierarchy from highest precedence to lowest precedence:
- Parentheses are always respected
- Multiplication, division, and remainder
- Addition and subtraction
- Left to right when operators have the same precedence
First example:
fmt.Println(1 + 2 * 3) // Output: 7
Multiplication is executed before addition, so:
1 + 2 * 3 = 1 + 6 = 7
Second example:
fmt.Println((1 + 2) * 3) // Output: 9
What's inside parentheses is executed before multiplication, so:
(1 + 2) * 3 = 3 * 3 = 9
Third example:
fmt.Println(6 / 4 * 3 + 5) // Output: 8
Multiplication and division come before addition. They have the same priority, so they are executed from left to right. Because these are integers, 6 / 4 evaluates to 1:
6 / 4 * 3 + 5 = 1 * 3 + 5 = 3 + 5 = 8
Fourth example:
fmt.Println(6 / ((4 + 2) / 3)) // Output: 3
Go sees parentheses, so it evaluates the inner expression first:
6 / ((4 + 2) / 3) = 6 / x, where x = (4 + 2) / 3
Compute x first:
(4 + 2) / 3 = 6 / 3 = 2
Then replace x with 2:
6 / ((4 + 2) / 3) = 6 / 2 = 3
Assignment
Follow the Coding Tutorial and let's practice with operator precedence!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.
