Learn / Rust / Variables: safe by default

Rust, lesson 2 of 5

Variables: safe by default

let makes a variable:

fn main() {
    let lessons = 5;
    println!("Lessons: {}", lessons);
}

In Rust, a variable cannot change unless you say it may. Rust refuses to build this program:

fn main() {
    let score = 10;
    score = 20;
    println!("{}", score);
}

Rust refuses to build this.

Values that never change by surprise make programs easier to trust. When a value should change, mark it with mut (short for mutable):

fn main() {
    let mut score = 10;
    score = score + 5;
    println!("Score: {}", score);
}

You can also shadow a variable: a new let with the same name makes a fresh variable that replaces the old one.

fn main() {
    let size = 4;
    let size = size * 2;
    println!("{}", size);
}

Check yourself

1. Can a Rust variable be changed by default?

2. What happens if you change a variable that is not marked mut?

3. After let mut count = 1; count = count * 3; count = count + 1; what is count?

4. After let x = 5; let x = x + 1; what is x?