Module 1Variables & TypesLesson 4 of 1022 min
Variables, mut & Shadowing
let, mut, shadowing, and constants — immutability by default as a risk control.
Immutability is the default
rust
let price = 100.5;
// price = 101.0; // error: cannot assign twice to immutable variable
let mut volume = 1_000;
volume = 1_200; // okIn trading systems this default is a feature: fewer accidental overwrites of spot, seed, or nav.
Shadowing (re-bind with let)
Shadowing is not mutation — it creates a new variable that reuses the name:
rust
let n = "42"; // &str
let n: i32 = n.parse().expect("int"); // i32
let n = n + 1;Useful when transforming raw market strings into numbers.
Constants
rust
const TRADING_DAYS_US: u32 = 252;
const SECONDS_PER_DAY: u64 = 86_400;Constants must have an explicit type and be computable at compile time.
Worked example: position size
rust
fn main() {
const MAX_QTY: i64 = 10_000;
let mut qty = 1_000;
qty += 500;
if qty > MAX_QTY {
qty = MAX_QTY;
}
println!("qty={qty} (max {MAX_QTY})");
}Output
qty=1500 (max 10000)Exercise
Track a mutable quantity, clamp it, compute notional.
Challenge
Use shadowing to parse quantity from the string "350" then apply the same clamp logic.
Tips
- mut allows reassignment of the same binding
- shadowing can change types; mut cannot
- const names are SCREAMING_SNAKE by convention
Try it live
Variables, mut & ShadowingRust 2021
Loading editor…
Output
Press Run to compile and execute.