Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
When you need a variable that can change, use mut in Rust. In PHP, variables are mutable by default, so no extra keyword is needed.
Rust
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6; // Allowed because x is mutable
println!("The value of x is: {}", x);
let mut counter = 0;
counter += 1;
counter += 1;
println!("Counter: {}", counter); // 2
}
mut makes it clear where values can be modified. The compiler still enforces safety (e.g. no data races).
PHP
<?php
$x = 5;
echo "The value of x is: $x\n";
$x = 6; // Allowed, PHP variables are mutable by default
echo "The value of x is: $x\n";
$counter = 0;
$counter++;
$counter++;
echo "Counter: $counter\n"; // 2
In PHP, mutability is the default. There is no keyword to mark a variable as mutable.
Comparison
- Rust: Use
let mutfor mutable variables; mutation is explicit and compiler-checked. - PHP: Variables are mutable by default; no keyword needed.
Using mut in Rust makes mutation visible in the code and helps the compiler prevent unintended sharing or races.
References
What's next
Next: Shadowing.
From PHP to Rust — Rust Syntax and Functions