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:
- A variable declared inside a block cannot be used after that block ends. section 1.6 section 1.7
- The final expression without a semicolon becomes the block's value. section 1.6 section 1.7
- Adding a semicolon turns that final expression into the unit value (), meaning nothing is returned. section 1.6 section 1.7
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




