スコープとシャドーイング

変数のスコープは、囲まれたブロック内に限定されます。

外側のスコープの変数と、同じスコープの変数の両方をシャドーイングできます。

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 を追加し、そのブロックの外側でアクセスを試みることで、変数のスコープが制限されていることを示します。
  • Shadowing is different from mutation, because after shadowing both variables' memory locations exist at the same time. Both are available under the same name, depending where you use it in the code.
  • シャドーイング変数の型はさまざまです。
  • シャドーイングは一見わかりにくいように見えますが、.unwrap() の後の値を保持する場合に便利です。