Menu
Coddy logo textTech

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 icon

Challenge

Beginner

Write a Rust program that demonstrates the concept of shadowing. Perform the following steps:

  1. Declare a variable named x and initialize it with the value 5.
  2. Print the value of x to the console in the following format: x is: …
  3. Shadow x with a new value that is the original x plus 3 inside a new scope.
  4. Print the shadowed x  in the following format: x is: …
  5. Finally print x outside 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
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals