0
0
Rustprogramming~5 mins

Operator precedence in Rust

Choose your learning style9 modes available
Introduction
Operator precedence tells us which part of a math or logic expression to solve first, so the computer gets the right answer.
When you write math calculations with many operators like +, -, *, /.
When you combine conditions using && (and) and || (or) in if statements.
When you want to avoid mistakes in complex expressions by knowing what happens first.
When you use parentheses to change the order of operations.
When debugging why a calculation or condition gives an unexpected result.
Syntax
Rust
value1 operator1 value2 operator2 value3
Operators with higher precedence run before operators with lower precedence.
Use parentheses () to change the order and make it clear.
Examples
Multiplication (*) happens before addition (+), so 3*4=12 first, then 2+12=14.
Rust
let result = 2 + 3 * 4;
Parentheses () make addition happen first: 2+3=5, then 5*4=20.
Rust
let result = (2 + 3) * 4;
&& (and) has higher precedence than || (or), so false && false = false first, then true || false = true.
Rust
let is_true = true || false && false;
Sample Program
This program shows how Rust uses operator precedence: multiplication before addition, and && before ||.
Rust
fn main() {
    let a = 5 + 2 * 3;
    let b = (5 + 2) * 3;
    let c = true || false && false;
    println!("a = {}", a);
    println!("b = {}", b);
    println!("c = {}", c);
}
OutputSuccess
Important Notes
Remember: multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).
Logical AND (&&) has higher precedence than logical OR (||).
Use parentheses to make your code easier to read and avoid mistakes.
Summary
Operator precedence decides which parts of an expression run first.
Multiplication and division come before addition and subtraction.
Use parentheses to control or clarify the order.