learn-rust

Free Rust 🦀 course in English 🇬🇧

View on GitHub

Table of Contents📚

Shadowing👥

What is a shadowing❓

When we modify a variable inside a code block, the change will remain outside it, but it is possible to make the variable back to its original value when the code block ends. This is called shadowing.

Usage

For example, we can use a code block to modify a variable:

let worm_name = "Wormie 🪱";

{
    worm_name = "Wormy 🪱";
    println!("My Worm is called {}", worm_name);
}

println!("My Worm is called {}", worm_name);

Output:

My Worm is called Wormy 🪱
My Worm is called Wormy 🪱

We can see that the change of the variable worm_name is still available outside the code block. We can shadow the variable with a new one inside the code block by adding the let keyword before the variable name.

let worm_name = "Wormie 🪱";

{
    let worm_name = "Wormy 🪱";
    println!("My Worm is called {}", worm_name);
}

println!("My Worm is called {}", worm_name);

Output:

My Worm is called Wormie 🪱
My Worm is called Wormy 🪱

Home 🏠 - Next Section ⏭️


Course created by SkwalExe and inspired by Dcode