Skip to main content
Module 1 · Lesson 1 of 21/24 in the course~15 min
Module lessons (1/2)

Variables, let mut, const and Shadowing

Warm-Up Stage

Immutability by default

Write predictable code where each mutation is declared explicitly at the root.

In many languages, variables are editable by default, and it is up to the programmer to remember who might alter their value later. Rust reverses this approach: every binding created with let is immutable by default, eliminating entire classes of bugs due to accidental changes.

1. Immutable bindings with let

When you assign a value with let, the compiler prevents any subsequent reassignment on the same identifier:

Rust
fn main() {
    let server_port = 8080;
    println!("Porta configurata: {}", server_port);

    // Decommentare la riga sotto produce error[E0384]:
    // server_port = 9090;
}

The default immutability makes it immediately obvious to the reader (and the rustc optimizer) which values remain constant throughout the entire execution block.

2. Explicit mutability with let mut

When a counter or accumulator needs to change state over time, add the mut keyword:

Rust
fn main() {
    let mut retries = 0;
    println!("Tentativi iniziali: {}", retries);

    retries += 1;
    retries += 1;
    println!("Tentativi dopo backoff: {}", retries);
}
KeywordEditableType changeAssessment
let xNoNoRuntime
let mut xYesNoRuntime
let x (king)New letYesRuntime (Shadowing)
const XNeverNoCompile time (&'static)

3. Compile-time constants (const)

A constant const can live in global scope outside of main(), always requires explicit type annotation, and the compiler replaces its value directly inline where it is used:

Rust
const MAX_CONNECTIONS: u32 = 100;
const TIMEOUT_SECS: u64 = 30;

fn main() {
    let active = 12;
    println!("Connessioni {}/{} (timeout {}s)", active, MAX_CONNECTIONS, TIMEOUT_SECS);
}

4. Shadowing: Transforming values and types into security

shadowing consists of re-declaring a new let with the same name. Unlike let mut, you can even change the type of the variable while keeping the name readable after the transformation is complete:

Rust
fn main() {
    let raw_input = "  42  ";
    let raw_input = raw_input.trim();
    let parsed_count: i32 = raw_input.parse().unwrap_or(0);

    let spaces = "   ";
    let spaces = spaces.len(); // da &str a usize con lo stesso nome

    println!("Conteggio: {}, spazi: {}", parsed_count, spaces);
}

Practical exercises

Exercise#rust.m1.l1.e1
Attempts: 0Loading…

Declare a global constant MAX_USERS: u32 = 500, then inside main create a mutable variable active_users initialized to 10, increment it by 5, and print it.

Loading editor…
Show hint

Use const MAX_USERS: u32 = 500; outside main, and let mut active_users = 10; active_users += 5; inside main.

Solution available after 3 attempts

Exercise#rust.m1.l1.e2
Attempts: 0Loading…

Use shadowing to convert the string raw_port = "8080" first to .trim() and then to the numeric type u16 via .parse::<u16>().unwrap(), finally printing raw_port.

Loading editor…
Show hint

Write let raw_port = raw_port.trim(); followed by let raw_port: u16 = raw_port.parse::<u16>().unwrap();.

Solution available after 3 attempts

Exercise#rust.m1.l1.e4
Attempts: 0Loading…

Write a function bump_counter(base: i32, delta: i32) -> i32 that creates a local accumulator let mut acc = base;, shadows an optional doubling or sum delta before returning acc.

Loading editor…
Show hint

Initialize let mut acc = base;, add acc += delta;, and return acc without trailing ;.

Solution available after 3 attempts

Check for understanding

Rust Quiz#rust.m1.l1.e3
Ready

What does compiling the following Rust code do?

Rust
fn main() {
    let mut label = "hello";
    label = label.len();
}
Answer options
Rust Quiz#rust.m1.l1.e5
Ready

Which statement about the constants const in Rust is correct?

Rust
const BUFFER_BYTES: usize = 4096;
Answer options