let / mut / const / static
In Rust, variables are declared with let and are immutable by default. Use mut to make a variable mutable. const and static define constants and static variables that are valid throughout the entire program.
Syntax
// Immutable variable let variable_name: Type = value; let variable_name = value; // Uses type inference. // Mutable variable let mut variable_name = value; // Constant (type annotation required; evaluated at compile time) const CONSTANT_NAME: Type = value; // Static variable (has a fixed memory location valid for the entire program) static VARIABLE_NAME: Type = value; // Shadowing (re-declares a variable with the same name) let variable_name = value; let variable_name = new_value; // Hides the previous variable.
Declaration Types
| Declaration | Mutability | Description |
|---|---|---|
| let x = value | Immutable | The default variable declaration. Reassignment is not allowed. |
| let mut x = value | Mutable | A variable that can be reassigned and modified. |
| const NAME: Type = value | Immutable | A constant evaluated at compile time. A type annotation is required. |
| static NAME: Type = value | Immutable | A static variable with a fixed memory address. Has a 'static lifetime. |
| Shadowing | Immutable → Immutable | Re-declares a variable with the same name, allowing you to change its value or type. The original variable is hidden. |
Sample Code
const MAX_POINTS: u32 = 100_000;
static GREETING: &str = "Hello";
fn main() {
// Immutable variable
let x = 5;
// x = 6; // Error: cannot assign to immutable variable.
// Mutable variable
let mut y = 5;
y = 6; // Reassignment is allowed.
println!("y = {}", y); // Prints "6".
// Type inference
let z = 3.14; // Inferred as f64.
println!("z = {}", z);
// Shadowing (the type can also change)
let spaces = " "; // &str type
let spaces = spaces.len(); // usize type (the type has changed)
println!("spaces = {}", spaces); // Prints "3".
// Converting with shadowing
let mut count = 0;
count += 1;
let count = count; // Locks the mutable variable as immutable.
println!("MAX: {}", MAX_POINTS);
println!("{}", GREETING);
println!("count: {}", count);
}
Notes
Because variables are immutable by default in Rust, unintended modifications are prevented. Using mut only when mutability is truly needed makes the intent of your code explicit.
Shadowing differs from mut in that it is useful for type conversion and reuse of names within a scope. However, when shadowing a mut variable to remove its mutability, it is a good idea to leave an explicit comment explaining your intent.
You can use underscores (_) as separators in numeric literals (e.g., 100_000).
If you find any errors or copyright issues, please contact us.