Rust by Example: Variables and Mutability
Learn how Rust handles variable assignments with its unique approach to immutability. This example covers declaring variables with 'let', making them mutable with 'mut', and the powerful concept of variable shadowing.
Code
fn main() {
// 1. Immutable variable (default)
let x = 5;
println!("The value of x is: {}", x);
// x = 6; // This would cause a compile error!
// 2. Mutable variable
let mut y = 10;
println!("The value of y is: {}", y);
y = 20; // This is allowed because y is mutable
println!("The value of y is now: {}", y);
// 3. Shadowing
let z = 100;
let z = z + 1; // New variable 'z' shadows the old one
let z = z * 2;
println!("The value of z is: {}", z);
}Explanation
In many programming languages, variables are mutable (changeable) by default. Rust takes a different approach: variables are immutable by default. This is a core design choice to enhance safety and concurrency. When you declare let x = 5;, you are making a promise that x will always equal 5. If you try to change it later, the compiler will stop you, preventing a whole class of bugs related to unexpected state changes.
However, mutability is often necessary. To make a variable mutable, you must explicitly use the mut keyword, as in let mut y = 10;. This explicit opt-in makes your code's intent clear: "I intend for this value to change." It signals to both the compiler and future readers of your code that this variable requires extra attention regarding its state.
Rust also introduces a powerful concept called Shadowing. This allows you to declare a new variable with the same name as a previous one, effectively "shadowing" the old variable.
- Re-binding: Unlike
mut, which changes the value in the same memory location, shadowing creates a new variable in a new stack slot (conceptually). - Type Changing: Because it's a new variable, you can change the type! You can shadow a string
"42"with its integer parsed value42, reusing the nameinput. - Immutability: The new shadowed variable is immutable by default, even if the original was mutable.
Code Breakdown
let x = 5; declares an immutable variable. Any attempt to reassign x later in the scope will result in a compilation error "cannot assign twice to immutable variable".let mut y = 10; declares a mutable variable. The mut keyword is required if you want to change the value bound to y later.y = 20; reassigns the value. This is valid only because y was declared with mut. Note that the type of y cannot change, only its value.let z = ... repeatedly. This is shadowing. We are creating a new variable z each time, which hides the previous one. This allows us to perform transformations and keep the variable immutable at each step.
