代码块和作用域

A block in Rust contains a sequence of expressions, enclosed by braces {}. Each block has a value and a type, which are those of the last expression of the block:

fn main() {
    let z = 13;
    let x = {
        let y = 10;
        dbg!(y);
        z - y
    };
    dbg!(x);
    // dbg!(y);
}

If the last expression ends with ;, then the resulting value and type is ().

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

This slide should take about 5 minutes.
  • You can explain that dbg! is a Rust macro that prints and returns the value of a given expression for quick and dirty debugging.

  • 你可以通过更改块的最后一行,来展示块值的变化情况。例如,添加/移除分号或使用 return

  • Demonstrate that attempting to access y outside of its scope won’t compile.

  • Values are effectively “deallocated” when they go out of their scope, even if their data on the stack is still there.