Module lessons (1/2)
Variables, let mut, const and Shadowing
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:
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:
fn main() {
let mut retries = 0;
println!("Tentativi iniziali: {}", retries);
retries += 1;
retries += 1;
println!("Tentativi dopo backoff: {}", retries);
}| Keyword | Editable | Type change | Assessment |
|---|---|---|---|
let x | No | No | Runtime |
let mut x | Yes | No | Runtime |
let x (king) | New let | Yes | Runtime (Shadowing) |
const X | Never | No | Compile 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:
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:
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
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.
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
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.
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
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.
Show hint
Initialize let mut acc = base;, add acc += delta;, and return acc without trailing ;.
Solution available after 3 attempts
Check for understanding
What does compiling the following Rust code do?
fn main() {
let mut label = "hello";
label = label.len();
}Which statement about the constants const in Rust is correct?
const BUFFER_BYTES: usize = 4096;