Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
In Rust, variables are immutable by default. Once you assign a value, it cannot be changed unless you explicitly use mut. This is the opposite of PHP, where variables are mutable unless you use const or readonly.
Rust
fn main() {
let x = 5;
println!("The value of x is: {}", x);
// x = 6; // Compile error: cannot assign twice to immutable variable
}
You declare a variable with let. Without mut, reassignment is forbidden and the compiler will catch it.
PHP
In PHP, variables are mutable by default. To get immutability you use constants or (from PHP 8.1+) readonly class properties:
<?php
$x = 5;
echo "The value of x is: $x\n";
$x = 6; // Allowed in PHP, variables are mutable by default
echo "The value of x is: $x\n";
// For immutability, use constants (but they're global)
const MAX_COUNT = 100;
// MAX_COUNT = 200; // Fatal error: Cannot redefine constant
Comparison
- Rust: Variables are immutable by default; use
letwithoutmut. Reassignment is a compile error.constis block-scoped. - PHP: Variables are mutable by default. Use
constfor immutability, but PHP constants are global.
Rust's default immutability reduces accidental changes and makes it easier to reason about code.
References
What's next
Next: Mutable variables.
From PHP to Rust — Rust Syntax and Functions