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);
}