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 variable in Rust is a named binding to a specific memory location, established using the let keyword. By default, variable bindings in Rust are strictly immutable, meaning their assigned value or underlying data cannot be modified after initialization. Rust enforces strong, static typing with aggressive type inference, resolving types at compile-time.

Syntax and Type Inference

Variables are declared using let. The compiler infers the type based on the assigned value. If explicit typing is required, it is appended after the variable name using a colon (:).
// Implicit type inference (defaults to i32 for integers)
let x = 10;

// Explicit type annotation
let y: f64 = 3.14;

Mutability

To allow reassignment or modification of a variable’s data, the binding must be explicitly declared as mutable using the mut keyword. This alters the binding’s contract with the compiler, permitting in-place memory mutation.
// Immutable binding (default)
let a = 5;
// a = 6; // Compiler error: cannot assign twice to immutable variable

// Mutable binding
let mut b = 5;
b = 6; // Valid reassignment

Shadowing

Rust permits variable shadowing, where a subsequent let declaration utilizes the exact same name as an existing variable in the current or parent scope. Shadowing allocates a completely new variable, allowing for type transformations while maintaining immutability. The previous variable is obscured until the current scope terminates.
let z = "hello";

// Shadowing 'z' with a new type (usize) and value
let z = z.len(); 

// Shadowing within an inner scope
{
    let z = z * 2;
} // Inner 'z' is dropped; outer 'z' is accessible again

Scope and Initialization

Variables possess lexical scope, remaining valid from the point of declaration until the end of the enclosing block ({}). Rust guarantees memory safety by enforcing strict initialization; a variable must be assigned a value before its memory is read.
let uninitialized_var: i32;

// println!("{}", uninitialized_var); // Compiler error: use of possibly-uninitialized variable

// Deferred initialization is valid as long as it occurs before the first read
uninitialized_var = 100; 

Variables vs. Constants

Variables (let) differ fundamentally from constants (const). Constants are evaluated at compile-time, are perpetually immutable (cannot use mut), require explicit type annotations, and can be declared in the global scope.
// Constant declaration
const MAX_CAPACITY: u32 = 100_000;
Master Rust with Deep Grasping Methodology!Learn More