ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Rust Tutorial• 6 min read

Variables, Mutability & Variable Shadowing

let vs let mut, typed constants, and the power of shadowing

In Rust, variables are strictly IMMUTABLE by default. Mutability must be explicitly opted into using the mut keyword.

Mutability vs Shadowing

let x = 5;: Immutable. Attempting x = 6 produces a compile error.

let mut x = 5;: Explicitly mutable.

Variable Shadowing: Declaring a new variable with the same name (let spaces = " "; let spaces = spaces.len();) transforms types and values safely while keeping the resulting variable immutable.

Mutability and Shadowing in Rust
fn main() {
    let mut score = 50;
    score += 25; // Allowed because of 'mut'
    println!("Score: {}", score);

    // Shadowing: Re-declaring 'input' with a new type!
    let input = "  42  ";
    let input: u32 = input.trim().parse().expect("Failed to parse");
    println!("Parsed number: {}", input);
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What keyword must be added to a variable declaration in Rust to allow its value to be reassigned?