Start learning free

LESSON 21 OF 348 · CALCULATIONS WITH NUMBERS

Operator Precedence in Rust in Rust

Lesson

TL ; DR:

  • When we string operations together, Rust must know which one to do first. This is called operator precedence.


  • * and / are performed before + and -:

  • println!("{}", 1 + 2 * 3); // Prints 7
    println!("{}", 6 - 4 / 2); // Prints 4
    println!("{}", 5 * 4 - 2 / 2); // Prints 19
    

  • We can add () to force an operation to be performed first:

    println!("{}", (1 + 2) * 3); // Prints 9
    println!("{}", (6 - 4) / 2); // Prints 1
    println!("{}", 5 * (4 - 2) / 2); // Prints 5
    


Full lesson:

When we string operations together, Rust 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
  • Exponentiation (raise to a power)
  • Multiplication, Division and Remainder
  • Addition and Subtraction
  • Left to right


First example:

println!("{}", 1 + 2 * 3); // Output: 7

Multiplication is executed before addition, so:

1 + 2 * 3 = 1 + 6 = 7

Second example:

println!("{}", (1 + 2) * 3); // Output: 9

What's inside parentheses is executed before multiplication, so:

(1 + 2) * 3 = 3 * 3 = 9

Third example:

println!("{}", 6.0 / 4.0 * 3.0 + 5.0); // Output: 9.5

Multiplication and division come before addition. Also, multiplication and division have the same priorty so they are executed from left to right:

6 / 4 * 3 + 5 = 1.5 * 3 + 5 = 4.5 + 5 = 9.5

Forth example:

println!("{}", 6 / ((4 + 2) / 3)); // Output: 3

Computer sees parentheses so it looks at it like this:

6 / ((4 + 2) / 3) = 6 / x, where x = (4 + 2) / 3

I have to compute x first. Parantheses are executed before division:
(4 + 2) / 3 = 6 / 3 = 2

I can 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.


STEP 1 OF 1
    Ctrl + Enter to check

    Operator Precedence in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free