Variables & Immutability β Why Ruby's Free Reassignment Disappears
let, mut, shadowing, const β side-by-side with Ruby variables
In Ruby, x = 10 can become x = 20 at any time. Rust is different. let x = 10; makes this value immutable. Try to change it and you get a compile error.
let x = 10;
// x = 20; // error[E0384]: cannot assign twice to immutable variable
Think of Ruby's freeze applied to every variable by default.
mut β explicit mutability
Want to change a value? Add mut.
let mut x = 10;
x = 20; // OK
It tells the reader "this variable will change." In Ruby, every variable is implicitly mut. Rust demands you state your intent.
shadowing β redeclaring with the same name
In Ruby, x = "hello" can become x = 42 β even changing types. Rust's equivalent is shadowing.
let x = "hello"; // &str
let x = x.len(); // usize β type change is fine
let x = x + 1; // shadows previous x
The difference from mut: shadowing creates a new variable. The previous x is gone. mut changes the value of the same variable.
// mut can't change the type
let mut x = "hello";
// x = 5; // compile error! type mismatch
// shadowing can change the type
let x = "hello";
let x = 5; // OK β new variable
Shadowing feels more natural to Rubyists. It's common in Rust too β especially when parsing a string into a number and reusing the same name.
const β Ruby's CONSTANT
Like Ruby's MAX_SIZE = 100, Rust uses const for constants.
const MAX_SIZE: usize = 100;
Differences from let:
constrequires explicit type annotationconstvalues must be known at compile timeconstworks anywhere (outside functions too)
In Ruby, reassigning a constant gives a warning but runs. In Rust, const reassignment is impossible.
Summary
| Ruby | Rust | Note |
|---|---|---|
x = 10 |
let x = 10; |
immutable |
x = 10; x = 20 |
let mut x = 10; x = 20; |
mutable |
x = "hi"; x = 42 |
let x = "hi"; let x = 42; |
shadowing |
MAX = 100 |
const MAX: usize = 100; |
constant |
Key Points
let is immutable by default β like Ruby freeze being the default
Add mut for mutability β all Ruby variables are implicitly mut
Shadowing creates a new variable with the same name β type can change
const is a compile-time constant β stricter than Ruby CONSTANT
Pros
- ✓ Immutable default prevents unintended value changes at the source
- ✓ Shadowing allows flexible variable reuse like Ruby
Cons
- ✗ Tendency to add mut by habit β Rust convention prefers immutable when possible
- ✗ Overusing shadowing can confuse when same name holds different values