محدوده‌ها و سایه‌گذاری

A variable’s scope is limited to the enclosing block.

شما می توانید متغیرها را سایه بزنید، هم آنهایی که از اسکوپ‌های بیرونی هستند و هم متغیرهایی که از اسکوپ یکسان هستند:

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() مناسب است.