Shadowing Part 1
Part of the Fundamentals section of Coddy's Rust journey — lesson 46 of 75.
You can declare a new variable with the same name as a previous variable in a different scope. The new variable shadows the previous one until the end of its scope:
fn main() {
let x = 5;
{
let x = 12;
// shadows the outer x
println!("{}", x);
// prints "12"
}
println!("{}", x);
// prints "5"
}Challenge
BeginnerWrite a Rust program that demonstrates the concept of shadowing. Perform the following steps:
- Declare a variable named
xand initialize it with the value5. - Print the value of
xto the console in the following format:x is: … - Shadow
xwith a new value that is the originalxplus3inside a new scope. - Print the shadowed
xin the following format:x is: … - Finally print
xoutside of the scope in the following format:x is: …
Cheat sheet
You can declare a new variable with the same name as a previous variable in a different scope. The new variable shadows the previous one until the end of its scope:
fn main() {
let x = 5;
{
let x = 12;
// shadows the outer x
println!("{}", x);
// prints "12"
}
println!("{}", x);
// prints "5"
}Try it yourself
fn main() {
// Declare x and initialize it with 5
// Print the value of x
{
// Shadow x with the original x plus 3
// Print the value of the shadowed x
}
// Print the value of outer x
}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