Key Concepts
- Variables are immutable by default.
- Use
mutfor mutability. - Constants with
constare always immutable and require types. - Shadowing redeclares variables with
let, allowing type changes.
1. Immutable vs. Mutable Variables
fn main() {
let x = 5;
println!("The value of x is: {x}");
// x = 6; // Error!
}
Mutable:
fn main() {
let mut x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
2. Constants
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
3. Shadowing
fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("Inner: {x}"); // 12
}
println!("Outer: {x}"); // 6
}
4. Shadowing with Type Change
let spaces = " ";
let spaces = spaces.len(); // Now usize
Rust's immutability enhances safety and concurrency.
You Try
Edit the shadowing example below (e.g., change values or add more shadowing) and click Run to see the outputs.
fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("Inner: {x}"); // 12
}
println!("Outer: {x}"); // 6
}