Scope and initialization
Quick answer
Scope determines where a name can be used. A local binding introduced inside a block is available only within its scope. Rust also requires a binding to be initialized on every applicable path before it is read.
Blocks and initialization
Braces create a block, which may contain local bindings. Inner code can use outer names; a name created in an inner block is not visible after the block ends. A declaration let value: i32; may be initialized once later, but reading it before assignment is an error.
fn main() { let outer = 10; { let inner = outer + 2; println!("{inner}"); } println!("{outer}");}Expected stdout (not executed):
1210The outer name remains available after the inner block.
fn main() { let result: i32; result = 4 * 3; println!("{result}");}Expected stdout (not executed):
12A first assignment initializes the previously uninitialized binding.
Common mistake
Do not read inner outside its block or read result before assigning it. The compiler rejects both cases.
Try it yourself
Create a block that uses an outer quantity to calculate a temporary total, then print the outer quantity after the block.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Scope and initialization — practice quiz
Choose one answer per question, then review the explanation.
Does `let n: i32; n = 6; println!("{n}");` compile inside main?
What is printed by `let outer = 4; { let inner = outer + 1; println!("{inner}"); }`?
What is wrong with `let n: i32; println!("{n}");`?