liveBook · Manning

Block

As explained in Learn Rust in a Month of Lunches

A code block is a delimited sequence of Rust statements and expressions that forms a lexical scope and produces a value.

A code block is a section of Rust code enclosed in braces. It creates a scope: variables declared inside it live only until the block ends. Blocks can also produce a value, so they can be used wherever an expression is expected. section 1.6 section 1.7

Keep these rules in mind:

Return a value from a block

let my_number = { let second_number = 8; second_number + 9 }; println!("My number is: {}", my_number); section 1.7

fn main() {
    let my_number = {
    let second_number = 8;
        second_number + 9     #1
    };
 
    println!("My number is: {}", my_number);
}

Shows a local variable used inside a block and the block's final expression assigned to an outer variable. section 1.7

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines scope and return behavior through small examples, then stops short of deeper ownership or lifetime analysis.
Examples
Uses nested numeric blocks, out-of-scope variables, arithmetic block values, and functions returning integers.
What it assumes
Assumes only basic Rust syntax and teaches declarations, scopes, lifetimes, semicolons, and implicit returns from zero.
What you can do after
Apply code blocks to limit variable scope and compute values, using compiler feedback to correct semicolon and lifetime mistakes.
How it connects
Connects code blocks to lexical scope, variable lifetime, expressions, semicolons, functions, and compiler errors.

Also explained in

Compare how 5 books explain block →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.