Rust:Rust Default Immutability, the mut Modifier, and Shadowing
Rust•Variables

Rust Default Immutability, the mut Modifier, and Shadowing

In Rust, variables are strictly immutable by default. This foundational design guarantee eliminates data races, accidental state mutation, and concurrency hazards at compile time. When mutation is required, the programmer must explicitly declare let mut. Furthermore, Rust supports variable shadowing, allowing re-declaration of the same identifier with a new type or transformed state without mutating the original binding.

Syntax

let max_threads = 8; // Immutable binding let mut active_jobs = 0; // Mutable binding let input_data = "42"; let input_data: u32 = input_data.parse().unwrap(); // Shadowing

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
letKeywordBinds a value to an immutable identifier by default.
mutModifierExplicitly allows reassigning and mutating the bound value.
ShadowingCompiler FeatureRe-declaring an existing variable name with let, optionally transforming its type.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

fn main() {
    println!("=== Rust Variable Binding & Mutability Specs ===");

    // 1. Default Immutable Binding
    let cluster_id = "rust-compute-node-alpha";
    println!("Cluster Identifier: {}", cluster_id);
    // cluster_id = "node-beta"; // COMPILE ERROR: cannot assign twice to immutable variable

    // 2. Explicit Mutable Binding with 'mut'
    let mut worker_count = 12;
    println!("Initial Workers:    {}", worker_count);
    worker_count += 4; // Permitted mutation
    println!("Scaled Workers:     {}", worker_count);

    // 3. Variable Shadowing (Preserving Immutability while Re-binding)
    let buffer_size = "2048";
    println!("Raw Buffer String:  {} bytes (Type: &str)", buffer_size);

    // Shadowing converts &str to parsed numeric usize without declaring a new name
    let buffer_size: usize = buffer_size.parse().expect("Failed to parse numeric value");
    let total_capacity_kb = buffer_size * 4 / 1024;
    println!("Parsed Buffer:      {} bytes (Calculated: {} KB)", buffer_size, total_capacity_kb);

    // 4. Scoped Shadowing
    let security_tier = 1;
    {
        let security_tier = security_tier + 2; // Shadowed within inner block
        println!("Inner Enclave Tier: {}", security_tier);
    }
    println!("Outer Standard Tier: {}", security_tier); // Remains 1
}
Expected Output:
=== Rust Variable Binding & Mutability Specs ===
Cluster Identifier: rust-compute-node-alpha
Initial Workers:    12
Scaled Workers:     16
Raw Buffer String:  2048 bytes (Type: &str)
Parsed Buffer:      2048 bytes (Calculated: 8 KB)
Inner Enclave Tier: 3
Outer Standard Tier: 1

How It Works: Step-by-Step

  • Lines 5-6: Declares immutable binding cluster_id; attempting reassignment is a compile error.
  • Lines 10-13: Declares worker_count with mut, permitting in-place += increment.
  • Lines 16-21: Demonstrates shadowing: re-declares buffer_size as usize, parsing the original string.
  • Lines 24-29: Illustrates block-scoped shadowing where the inner binding does not mutate the outer binding.

Key Concepts

  • Variables in Rust are immutable by default to make concurrent and systems programming safe and predictable.
  • The mut modifier signals to both the compiler and code reviewers that internal state will change across time.
  • Shadowing is distinct from mutability: shadowing creates an entirely new variable with let, which can even change data types.
  • Once an immutable variable is initialized, the compiler guarantees its memory content will never be modified in that scope.

Common Mistake: Attempting to reassign an immutable variable without mut

In Rust, attempting to reassign or modify a variable declared with let (and not let mut) triggers a compile-time error.

❌ Incorrect
let score = 100;
score = 150; // Compile Error: cannot assign twice to immutable variable
✅ Correct
let mut score = 100;
score = 150; // Correct: explicitly marked mutable

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler