2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
|
minutes: 5
|
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
# Variables
|
|
|
|
|
|
|
|
|
|
Rust provides type safety via static typing. Variable bindings are made with
|
|
|
|
|
`let`:
|
|
|
|
|
|
2025-01-20 12:47:50 -05:00
|
|
|
```rust,editable,warnunused
|
2023-11-29 10:39:24 -05:00
|
|
|
fn main() {
|
|
|
|
|
let x: i32 = 10;
|
|
|
|
|
println!("x: {x}");
|
|
|
|
|
// x = 20;
|
|
|
|
|
// println!("x: {x}");
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
<details>
|
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- Uncomment the `x = 20` to demonstrate that variables are immutable by default.
|
2023-11-29 10:39:24 -05:00
|
|
|
Add the `mut` keyword to allow changes.
|
|
|
|
|
|
2025-01-20 12:47:50 -05:00
|
|
|
- Warnings are enabled for this slide, such as for unused variables or
|
|
|
|
|
unnecessary `mut`. These are omitted in most slides to avoid distracting
|
|
|
|
|
warnings. Try removing the mutation but leaving the `mut` keyword in place.
|
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- The `i32` here is the type of the variable. This must be known at compile
|
2023-11-29 10:39:24 -05:00
|
|
|
time, but type inference (covered later) allows the programmer to omit it in
|
|
|
|
|
many cases.
|
|
|
|
|
|
|
|
|
|
</details>
|