← Back to Rust Course | Chapter 4: Functions | Lesson 3 of 6

Expressions vs Statements

In Rust, some lines of code hand back a value (expressions) and some just do something and end (statements).

What Is a Statement

A statement performs an action but does not itself evaluate to a value. Variable declarations with let are statements -- you cannot use let x = 5; as a value.

Example: What Is a Statement

markup
fn main() {
    let x = 5; // this whole line is a statement
    println!("x = {}", x);
}

What Is an Expression

An expression evaluates to a value. Simple examples include 5 + 6 or a function call like square(4), both of which produce a usable value.

Example: What Is an Expression

markup
fn main() {
    let sum = 5 + 6; // 5 + 6 is an expression
    println!("sum = {}", sum);
}

Blocks as Expressions

A block enclosed in { } is itself an expression: if its final line has no trailing semicolon, that line's value becomes the value of the whole block.

Example: Blocks as Expressions

markup
fn main() {
    let y = {
        let a = 3;
        a * a // no semicolon: this is the block's value
    };
    println!("y = {}", y);
}

Why the Semicolon Matters

Adding a semicolon after an expression turns it into a statement that evaluates to the unit type (). This is why forgetting or adding a stray semicolon on a function's last line changes whether it returns a value.

Example: Why the Semicolon Matters

markup
fn plus_one(x: i32) -> i32 {
    x + 1 // no semicolon, so this value is returned
}

fn main() {
    println!("{}", plus_one(4));
}
Common Mistakes
  1. Adding a semicolon to what was meant to be the returned tail expression, accidentally turning it into a statement that returns ().
  2. Assuming an if/match block always needs return to produce a value, when the tail expression is often enough.
  3. Trying to assign the result of a statement (like a let binding) to another variable, since statements do not produce a usable value.
Chapter Summary
  • Statements perform an action and do not return a value; they typically end with a semicolon.
  • Expressions evaluate to a value, such as 5 + 6 or a block ending in a value-producing line without a semicolon.
  • Blocks { ... } are themselves expressions if their last line has no semicolon.
  • Understanding this distinction explains why removing or adding a semicolon can change a function's behavior.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.