Rust Tutorial · Rust Basics · Lesson 4 of 29
Rust Variables and Mutability
Declare variables with let, make them mutable with mut, shadow them, and use constants.
Immutable by default
let creates a variable that can't be changed unless you write let mut. This makes code easier to
reason about: if something changes, it says so.
fn main() {
let city = "Lisbon";
let mut visitors = 10;
visitors += 5;
println!("{city}: {visitors} visitors");
// city = "Porto"; // error: cannot assign twice to immutable variable
}
Output
Lisbon: 15 visitors
Run this on your computer — see “Get Started” for setup.
Shadowing and constants
- Declaring a new variable with the same name shadows the old one; it can even change the type.
constvalues are known at compile time and need a type:const MAX_USERS: u32 = 1_000;.
const MAX_RETRIES: u32 = 3;
fn main() {
let input = "42";
let input: i32 = input.parse().unwrap(); // shadowing: same name, new type
println!("parsed {} (max retries {MAX_RETRIES})", input * 2);
}
Output
parsed 84 (max retries 3)
Run this on your computer — see “Get Started” for setup.
Test yourself
How do you declare a variable you can change later?
let x = 5;var x = 5;let mut x = 5;mut x = 5;
Show answer
Answer: let mut x = 5;