代码块和作用域

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:

  1. fn main() {
  2. let z = 13;
  3. let x = {
  4. let y = 10;
  5. println!("y: {y}");
  6. z - y
  7. };
  8. println!("x: {x}");
  9. }

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

This slide and its sub-slides should take about 5 minutes.

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