Immutability by Default
In Rust, variables are immutable by default. This is one of the language's core design decisions to help you write safer code. Once a value is bound to a name, you cannot change that value.
rust
Mutability (mut)
If you want to be able to change a value, you must explicitly declare the variable as mutable using the
mut keyword.rust
Constants (const)
Wait! What's the difference between an immutable variable (
let) and a Constant (const)?- Mutability: You are never allowed to use
mutwithconst. Constants are always immutable. - Type Annotation: You must annotate the type of a constant.
- Timing: Constants are evaluated at compile-time. They can be declared in any scope, including the global scope.
rust
Variable Shadowing
Shadowing allows you to declare a new variable with the same name as a previous one. The new variable "shadows" the old one until it goes out of scope or is shadowed again.
rust
[!NOTE] Shadowing is different frommutbecause we are effectively creating a new variable. This allows us to change the type of the value while keeping the same name!
Summary
| Feature | Syntax | Mutable? | Scope |
|---|---|---|---|
| let | let x = 5; | No | Local |
| let mut | let mut x = 5; | Yes | Local |
| const | const X: u32 = 5; | Never | Global/Local |
| Shadowing | let x = "hi"; | Creating a new binding | Local |
| Default | Immutability-first for safety and concurrency | ||
| Type | Shadowing can change types; mut cannot! | ||
| Naming | Variables: snake_case; Constants: SCREAMING_SNAKE_CASE | ||
| Logic | Use mut only when necessary; use shadowing for transformations | ||
| Safety | Prevents accidental modifications in complex systems | ||
| Global | Only const (and static) can exist outside fn main | ||
| Performance | Shadowing has zero runtime overhead |