Bird
Raised Fist0
Rustprogramming~10 mins

Expression vs statement in Rust - Visual Side-by-Side Comparison

Choose your learning style10 modes available
Concept Flow - Expression vs statement
Start
↓
Is it an Expression?
No→It's a Statement
Yes↓
Evaluates to a value
↓
Can be part of larger expressions
↓
End
This flow shows how Rust code is classified as expressions or statements. Expressions produce values and can be used inside other expressions. Statements perform actions but do not return values.
Execution Sample
Rust
let x = 5;          // statement
let y = {           // expression block
  let z = x + 1;    // statement
  z * 2             // expression (last line returns value)
};
This Rust code shows statements and expressions: variable assignments are statements; the block returns a value as an expression.
Execution Table
StepCode LineTypeEvaluation/ActionResult/Value
1let x = 5;StatementAssign 5 to xx = 5
2let y = { ... };StatementEvaluate block expression to assign to yy = 12
2.1let z = x + 1;StatementCalculate x + 1 = 6, assign to zz = 6
2.2z * 2ExpressionCalculate 6 * 212
💡 All statements executed; block expression returns 12 assigned to y
Variable Tracker
VariableStartAfter Step 1After Step 2.1After Step 2.2Final
xundefined5555
zundefinedundefined666
yundefinedundefinedundefined1212
Key Moments - 2 Insights
Why does the block inside let y = { ... } count as an expression?
Because the last line inside the block is an expression (z * 2) that returns a value (12), the whole block acts as an expression. This is shown in execution_table rows 2.2 and 2 where the block returns 12.
Why can't we use let x = 5 as an expression?
Because 'let x = 5;' is a statement that performs assignment and does not return a value. This is why in execution_table row 1 it is labeled as a statement with no return value.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of variable z after step 2.1?
A5
B12
C6
Dundefined
💡 Hint
Check the variable_tracker row for z after step 2.1
At which step does the block expression return its value?
AStep 2.2
BStep 2.1
CStep 1
DStep 2
💡 Hint
Look at execution_table rows 2.2 and 2; the expression at 2.2 returns 12 used in 2
If we change 'z * 2' to 'z * 3' in the block, what will be the new value of y?
A12
B18
C9
D6
💡 Hint
Multiply z=6 by 3 instead of 2; see execution_table row 2.2 for calculation
Concept Snapshot
Expression vs Statement in Rust:
- Statement: performs action, no value returned (e.g., let x = 5;)
- Expression: evaluates to a value, can be part of other expressions
- Blocks { ... } are expressions if last line returns a value
- Assignments are statements, expressions produce values
- Expressions can be nested inside statements
Full Transcript
In Rust, code is either an expression or a statement. Statements do things like assign values but do not produce a value themselves. Expressions calculate and return values. For example, 'let x = 5;' is a statement assigning 5 to x. A block like '{ let z = x + 1; z * 2 }' is an expression because its last line returns a value. This value can be assigned to another variable, like y. Understanding this helps write clear Rust code that uses expressions and statements correctly.

Practice

(1/5)
1. In Rust, which of the following best describes an expression?
easy
A. It calculates a value and returns it.
B. It performs an action but does not return a value.
C. It is used only for declaring variables.
D. It is a comment explaining the code.

Solution

  1. Step 1: Understand what an expression does

    An expression in Rust always produces a value when evaluated.
  2. Step 2: Compare with statements

    Statements perform actions but do not return values, unlike expressions.
  3. Final Answer:

    It calculates a value and returns it. -> Option A
  4. Quick Check:

    Expression = returns value [OK]
Hint: Expressions always produce values; statements do not [OK]
Common Mistakes:
  • Confusing statements with expressions
  • Thinking expressions do not return values
  • Assuming all code lines are statements
2. Which of the following is a valid Rust statement?
easy
A. let x = 5;
B. 5 + 3
C. x * 2
D. println!("Hello")

Solution

  1. Step 1: Identify statements vs expressions

    Statements perform actions and often end with a semicolon, like variable declarations.
  2. 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.
  3. Final Answer:

    let x = 5; -> Option A
  4. Quick Check:

    Statements end with semicolon [OK]
Hint: Statements usually end with semicolons [OK]
Common Mistakes:
  • Missing semicolon for statements
  • Confusing macro calls without semicolon as statements
  • Thinking expressions are statements
3. What is the output of this Rust code?
fn main() {
    let x = 3;
    let y = {
        let z = x + 2;
        z * 2
    };
    println!("{}", y);
}
medium
A. 8
B. 10
C. 7
D. Compilation error

Solution

  1. 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.
  2. Step 2: Assign and print the value

    Variable y gets the value 10, which is printed by println!.
  3. Final Answer:

    10 -> Option B
  4. Quick Check:

    Block expression returns 10 [OK]
Hint: Blocks return last expression value without semicolon [OK]
Common Mistakes:
  • Assuming block returns unit () due to semicolon confusion
  • Miscomputing z or y values
  • Thinking println! returns a value
4. Identify the error in this Rust code snippet:
fn main() {
    let x = 5;
    let y = if x > 3 {
        x + 1;
    } else {
        x - 1
    };
    println!("{}", y);
}
medium
A. Variable x is not initialized
B. Missing semicolon after if expression
C. The if block returns unit type, causing a type mismatch
D. println! macro is used incorrectly

Solution

  1. Step 1: Analyze the if expression branches

    The if branch has x + 1; with a semicolon, making it a statement returning unit (). The else branch returns x - 1 without semicolon, an expression returning i32.
  2. Step 2: Understand type mismatch

    Because branches return different types (unit vs i32), Rust reports a type mismatch error for y.
  3. Final Answer:

    The if block returns unit type, causing a type mismatch -> Option C
  4. Quick Check:

    If branches must return same type [OK]
Hint: Remove semicolon in if branch to return value [OK]
Common Mistakes:
  • Adding semicolon after expressions in if branches
  • Ignoring type mismatch errors
  • Assuming println! causes error
5. You want to assign a variable 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?
hard
A. let result = if n > 0 { n + 2 } else { 0 };
B. let result = if n > 0 { n + 2; } else { 0; };
C. let result = if n > 0 { n + 2 } else { println!("Zero") };
D. let result = { if n > 0 { n + 2 } else { 0 } };

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    let result = { if n > 0 { n + 2 } else { 0 } }; -> Option D
  4. Quick Check:

    Block expression returns if expression value [OK]
Hint: Use blocks or if expressions without semicolons for values [OK]
Common Mistakes:
  • Adding semicolons inside if branches
  • Mixing expressions with statements causing type errors
  • Using println! where a value is expected
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard