Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
This section summarizes how variables and mutability work in Rust and PHP.
Key points
- Rust: Variables are immutable by default; use
mutfor mutation. See 2.1 Immutable variables, 2.2 Mutable variables - PHP: Variables are mutable by default; no
mutkeyword. - Rust: Shadowing reuses a name in a new scope; the old binding is hidden. See 2.3 Shadowing
- PHP: Reassignment overwrites; no true shadowing; block scope exists in functions.
- Rust: Type inference often removes the need for explicit types.
- PHP: Dynamic typing; optional type declarations for parameters and return values.
Comparison
- Immutability: Rust defaults to immutable; PHP defaults to mutable.
- Mutability: Rust requires explicit
mut; PHP allows any variable to be reassigned. - Shadowing: Rust permits redeclaration in the same scope; PHP reassigns.
- Scoping: Both use block scope; Rust has stricter lifetime rules.
References
What's next
Next: Data types and structures.
From PHP to Rust — Rust Syntax and Functions