Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A mutable variable in Rust is a named memory binding, explicitly declared with the mut keyword, that permits the reassignment of its value and the in-place modification of its underlying data after initial initialization. Because Rust enforces immutability by default to guarantee memory safety and concurrency, mutability must be explicitly opted into at the binding level.

Syntax

The mut keyword is placed immediately after the let keyword and before the variable identifier.
let mut identifier: Type = value;

Core Mechanics

1. Strict Type Adherence While mut allows the value of a variable to change, it does not allow the type to change. Rust is statically typed; the memory layout allocated for the variable is fixed at compile time.
let mut counter = 0; // Inferred as i32
counter = 1;         // Valid: Reassignment of the same type

// counter = "Done"; // Compiler Error: expected integer, found `&str`
2. Compound Data Modification When a compound data type (like a struct, enum, or tuple) is bound to a mutable variable, the mutability cascades to all of its fields and elements. Rust does not support field-level mutability modifiers on structs; the entire instance is either mutable or immutable based on its binding.
struct Point {
    x: i32,
    y: i32,
}

let mut p = Point { x: 0, y: 0 };
p.x = 5; // Valid: 'p' is mutable, so its fields can be modified
3. Prerequisite for Mutable Borrowing Rust’s borrow checker dictates that you cannot take a mutable reference (&mut T) to data unless the underlying variable binding is itself declared as mutable.
let mut value = 10;
let value_ref = &mut value; // Valid: 'value' is declared with 'mut'
*value_ref += 5;            // Dereference and modify

let strict_value = 10;
// let strict_ref = &mut strict_value; // Compiler Error: cannot borrow as mutable

Mutability vs. Shadowing

Mutability modifies the data within an existing memory location. This is mechanically distinct from variable shadowing, which uses the let keyword again to create an entirely new variable (and a new memory allocation) that happens to share the same identifier.
// Mutability: Reuses the same memory location, type must remain the same
let mut a = 5;
a = 10; 

// Shadowing: Creates a new memory location, type can change
let b = 5;
let b = "text"; 
Master Rust with Deep Grasping Methodology!Learn More