Skip to main content
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 (:).

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.

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.

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.

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.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More