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.

Create a free account to save this page, take notes and track your progress. Sign in

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.

let and let mut
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.
  • const values are known at compile time and need a type: const MAX_USERS: u32 = 1_000;.
Shadowing and const
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?

  1. let x = 5;
  2. var x = 5;
  3. let mut x = 5;
  4. mut x = 5;
Show answer

Answer: let mut x = 5;

Was this page helpful?