範圍和遮蔽

變數的有效範疇受限於封閉其變數的區塊。

您可以遮蔽變量,包括來自外部範圍以及來自同一範圍的變量:

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}");
}
  • 請說明變數的範疇受到限制,做法是在最後一個範例的內部區塊中新增 b,然後嘗試在該區塊外部存取 b
  • 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() 之後的值很方便。