Blocks

A block in Rust has a value and a type: the value is the last expression of the block:

  1. fn main() {
  2. let x = {
  3. let y = 10;
  4. println!("y: {y}");
  5. let z = {
  6. let w = {
  7. 3 + 4
  8. };
  9. println!("w: {w}");
  10. y * w
  11. };
  12. println!("z: {z}");
  13. z - y
  14. };
  15. println!("x: {x}");
  16. }

The same rule is used for functions: the value of the function body is the return value:

  1. fn double(x: i32) -> i32 {
  2. x + x
  3. }
  4. fn main() {
  5. println!("doubled: {}", double(7));
  6. }

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

Key Points:

  • The point of this slide is to show that blocks have a type and value in Rust.
  • You can show how the value of the block changes by changing the last line in the block. For instance, adding/removing a semicolon or using a return.