variablesrustshadowing

Access to shadowed variable in Rust


In Rust, is there a way to access the variable (that is declared in the main context) in the inner context while it is shadowed in the inner context?

Below is the code I tried. Looks like scope operator :: is not supported in Rust?

fn main() {
    let top_variable = 1;

    {
        println!("top variable in inner scope before shadowing = {}", top_variable);

        let top_variable = "abc";

        println!("top variable in the inner scope = {}", top_variable);
        println!("top variable accessed in the inner scope using scope parameter = {}", ::top_variable);
    }

    println!("top variable back in the main scope = {}", top_variable);
    let top_variable = 100;
    println!("top variable in the main scope and modified  = {}", top_variable);
}

Solution

  • In Rust, is there a way to access the variable (that is declared in the main context) in the inner context while it is shadowed in the inner context?

    no.

    Below is the code I tried. Looks like scope operator :: is not supported in Rust?

    It's perfectly well supported, it means "global path" so needs to be followed by a crate name (in edition 2018 and later).