2.13 Syntax Structures: Expressions and Statements

2.13.1 Expressions vs. Statements

Rust is an expression-based language.

  • Expression: Evaluates to a value.
  • Statement: Performs an action.
fn main() {
    let x = 5; // Statement with an expression

    let y = {
        let x = 3;
        x + 1 // Expression without semicolon
    }; // y is 4

    println!("x = {}, y = {}", x, y);
}

2.13.2 Semicolons

  • Adding a semicolon turns an expression into a statement that does not return a value.
  • Omitting the semicolon means the expression's value is returned.

2.13.3 Blocks

  • Blocks {} can be used as expressions.

2.13.4 Comparison with C

  • C distinguishes between expressions and statements but does not allow blocks to be expressions that return values.