Expression vs statement in Rust - Performance Comparison
We want to understand how the time it takes to run code changes when using expressions versus statements in Rust.
Which parts of the code repeat work and how does that affect speed?
Analyze the time complexity of the following code snippet.
fn main() {
let mut sum = 0;
for i in 1..=5 {
sum += i; // statement
}
let result = { 1 + 2 + 3 + 4 + 5 }; // expression
println!("Sum: {}, Result: {}", sum, result);
}
This code adds numbers using a loop (a statement) and also calculates a sum using an expression block.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for loop runs 5 times, adding numbers one by one.
- How many times: The loop repeats 5 times; the expression runs once.
As the number of items to add grows, the loop runs more times, but the expression runs once regardless.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 additions in loop, 1 expression evaluation |
| 10 | 10 additions in loop, 1 expression evaluation |
| 100 | 100 additions in loop, 1 expression evaluation |
Pattern observation: The loop's work grows with input size, but the expression's work stays the same.
Time Complexity: O(n)
This means the time grows directly with the number of loop steps; expressions that run once don't add to growth.
[X] Wrong: "Expressions always take more time than statements because they look complex."
[OK] Correct: Expressions can run once and be simple, while statements like loops repeat work many times, taking more time as input grows.
Understanding how expressions and statements affect time helps you explain code efficiency clearly and confidently in interviews.
"What if we replaced the fixed loop range with a user input number n? How would the time complexity change?"
Practice
expression?Solution
Step 1: Understand what an expression does
An expression in Rust always produces a value when evaluated.Step 2: Compare with statements
Statements perform actions but do not return values, unlike expressions.Final Answer:
It calculates a value and returns it. -> Option AQuick Check:
Expression = returns value [OK]
- Confusing statements with expressions
- Thinking expressions do not return values
- Assuming all code lines are statements
Solution
Step 1: Identify statements vs expressions
Statements perform actions and often end with a semicolon, like variable declarations.Step 2: Check each option
let x = 5; declares a variable and ends with a semicolon, so it's a statement. Options A and C are expressions without semicolons. println!("Hello") is a macro call but without a semicolon, so it's an expression.Final Answer:
let x = 5; -> Option AQuick Check:
Statements end with semicolon [OK]
- Missing semicolon for statements
- Confusing macro calls without semicolon as statements
- Thinking expressions are statements
fn main() {
let x = 3;
let y = {
let z = x + 2;
z * 2
};
println!("{}", y);
}Solution
Step 1: Evaluate the inner block expression
Inside the block, z = x + 2 = 3 + 2 = 5, then the block returns z * 2 = 5 * 2 = 10.Step 2: Assign and print the value
Variable y gets the value 10, which is printed by println!.Final Answer:
10 -> Option BQuick Check:
Block expression returns 10 [OK]
- Assuming block returns unit () due to semicolon confusion
- Miscomputing z or y values
- Thinking println! returns a value
fn main() {
let x = 5;
let y = if x > 3 {
x + 1;
} else {
x - 1
};
println!("{}", y);
}Solution
Step 1: Analyze the if expression branches
The if branch hasx + 1;with a semicolon, making it a statement returning unit (). The else branch returnsx - 1without semicolon, an expression returning i32.Step 2: Understand type mismatch
Because branches return different types (unit vs i32), Rust reports a type mismatch error for y.Final Answer:
The if block returns unit type, causing a type mismatch -> Option CQuick Check:
If branches must return same type [OK]
- Adding semicolon after expressions in if branches
- Ignoring type mismatch errors
- Assuming println! causes error
result to the value of a block that adds 2 to n only if n is positive, otherwise returns 0. Which code correctly uses expressions and statements?Solution
Step 1: Check if expressions return values
Options A and D both return values correctly. let result = if n > 0 { n + 2; } else { 0; }; has semicolons inside if branches, making them statements returning unit (). let result = if n > 0 { n + 2 } else { println!("Zero") };'s else branch calls println! which returns unit (), causing type mismatch.Step 2: Compare A and D
let result = if n > 0 { n + 2 } else { 0 }; assigns directly from if expression. let result = { if n > 0 { n + 2 } else { 0 } }; wraps the if expression inside a block, which is also an expression returning the if's value. Both are valid, but let result = { if n > 0 { n + 2 } else { 0 } }; explicitly shows block expression usage.Final Answer:
let result = { if n > 0 { n + 2 } else { 0 } }; -> Option DQuick Check:
Block expression returns if expression value [OK]
- Adding semicolons inside if branches
- Mixing expressions with statements causing type errors
- Using println! where a value is expected
Ready to prove it?
Pass the test and this pattern moves unknown
