Shadowing

From Rust Community Wiki
Jump to navigation Jump to search

Shadowing is the concept of re-using variable names. This can be done either in a new scope or in the same scope:

let x = 5;
let x = "hello, world!";
{
    let x = true;
}

With shadowing, a new variable is created, which can have a different type, mutability and lifetime. Even when a variable is shadowed, it is dropped at the end of its scope:

fn foo(x: i32) {
    {
        let x = true;
        // second x is dropped here
    }
    // first x is dropped here
}

Not only variables, but also macro_rules! based macros can be shadowed:

macro_rules! m {
    (1) => {};
}
m!(1);

macro_rules! m {
    (2) => {};
}
m!(2);