Rust Tutorial: Variables and Mutability
Learn how Rust handles variables: immutable by default, explicit mutation, shadowing, and constants.
Variables in Rust
Rust variables are immutable by default. That is not a limitation — it is a feature.
When data cannot change unexpectedly, bugs become far easier to find and reason about.
You must explicitly opt in to mutation with `mut`. This makes your intentions clear to anyone reading the code.
What you'll learn in this Rust variables and mutability tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 15 minutes.
- Your first variable — `let` creates a variable. By default it is immutable — you cannot change it after creation.
- Immutable means immutable — Try to change an immutable variable and see what Rust says.
- Making a variable mutable — `let mut` creates a variable you can change:
- Shadowing — Rust lets you declare a new variable with the same name — this is called *shadowing*.
- Shadowing changes type — One power of shadowing: the new variable can be a different type.
- Constants — Constants are like variables, but:
- Declare first, use later — You can declare a variable and assign it later — useful when the value depends on a condition.
- Type annotations — Rust usually infers the type. But you can be explicit:
Rust Variables and Mutability concepts covered
- Variables in Rust