Scope
Part of the Fundamentals section of Coddy's Rust journey — lesson 45 of 75.
A scope is a place between curly braces {} that variables or other form of declaration live.
For example:
fn main() {
let x = 5;
// x comes into scope
println!("x is {}", x);
} // x goes out of scope hereScopes can be nested within other scopes. Inner scopes can access variables from outer scopes, but not vice versa:
fn main() {
let outer = 42;
{ // new inner scope
let inner = 99;
println!("{}, {}", outer, inner);
} // inner goes out of scope here
// This would cause an error
// inner is not accessible here
// println!("{}", inner);
}Cheat sheet
A scope is a place between curly braces {} where variables live:
fn main() {
let x = 5;
// x comes into scope
println!("x is {}", x);
} // x goes out of scope hereScopes can be nested. Inner scopes can access outer scope variables, but not vice versa:
fn main() {
let outer = 42;
{ // new inner scope
let inner = 99;
println!("{}, {}", outer, inner);
} // inner goes out of scope here
// inner is not accessible here
}Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input