2023-11-29 10:39:24 -05:00
|
|
|
---
|
2024-02-06 15:48:56 -05:00
|
|
|
minutes: 5
|
2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
|
|
|
|
# Blocks and Scopes
|
|
|
|
|
|
|
|
## Blocks
|
|
|
|
|
2024-01-16 09:06:24 -05:00
|
|
|
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:
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
fn main() {
|
|
|
|
let z = 13;
|
|
|
|
let x = {
|
|
|
|
let y = 10;
|
|
|
|
println!("y: {y}");
|
|
|
|
z - y
|
|
|
|
};
|
|
|
|
println!("x: {x}");
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
If the last expression ends with `;`, then the resulting value and type is `()`.
|
|
|
|
|
|
|
|
<details>
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- 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`.
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
</details>
|