Language basics
Variables and mutability
In Rust, a variable declared with let is immutable by default. That is the opposite of Java, where you have to add final. To be able to change it, you say so explicitly with mut.
rust
fn main() { let rate = 0.03; // rate = 0.04; // erreur : cannot assign twice to immutable variable let mut notional = 1_000_000.0; notional = notional * 2.0; println!("rate = {rate}, notional = {notional}");}Shadowing lets you redeclare a variable with the same name using let. The new variable hides the old one, and can even change type. It is handy to transform a value step by step without inventing names like input2.
rust
fn main() { let spaces = " "; let spaces = spaces.len(); // &str devient usize println!("{spaces} espaces"); const DAYS_PER_YEAR: f64 = 365.0; println!("{DAYS_PER_YEAR}");}const requires an explicit type and a value known at compile time. Convention: UPPER_SNAKE_CASE.Your turn
This code does not compile. Fix it by changing as little as possible.
src/main.rs
fn main() { let total = 0; total = total + 10; total = total + 5; println!("{total}");}Read the error message: it suggests the fix itself.
solution
fn main() { let mut total = 0; total = total + 10; total = total + 5; println!("{total}");}total is reassigned, so it must be declared mut. rustc error messages are among the best around: get used to reading them in full.