作用域和遮蔽(Shadowing)

变量的作用域仅限于封闭代码块内。

你可以隐藏变量,位于外部作用域的变量和 相同作用域的变量都可以:

fn main() {
    let a = 10;
    println!("before: {a}");
    {
        let a = "hello";
        println!("inner scope: {a}");

        let a = true;
        println!("shadowed in inner scope: {a}");
    }

    println!("after: {a}");
}
  • Show that a variable's scope is limited by adding a b in the inner block in the last example, and then trying to access it outside that block.
  • Shadowing is different from mutation, because after shadowing both variable's memory locations exist at the same time. Both are available under the same name, depending where you use it in the code.
  • A shadowing variable can have a different type.
  • 隐藏起初看起来会有些晦涩,但是它很便于存 .unwrap() 之后的得到的值。