Module 02 Exercises — Variables, Types & Memory Basics
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, be able to answer these without looking anything up:
- What is the difference between
let xandlet mut x? - What can shadowing do that
mutcannot? - For a given value: is it entirely on the stack, or does it own heap data?
Type every snippet. The point of Part A is not the answers — it is that the compiler tells you when you were wrong, immediately, which is the fastest feedback loop you will ever have.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 2.1 — Fix the compile errors
Make this compile with the smallest possible change to each line:
fn main() {
let x = 5;
x = 6;
let y: u8 = 300;
let z: i32 = 4.5;
let s = 'hello';
}Solution
fn main() {
let mut x = 5;
x = 6;
let y: u16 = 300; // 300 doesn't fit in u8
let z: i32 = 4; // or: let z: f64 = 4.5;
let s = "hello"; // double quotes for &str
println!("{x} {y} {z} {s}");
}🟢 Exercise 2.2 — Shadowing vs mutation
Predict the output before running:
fn main() {
let x = 1;
let x = x + 1;
{
let x = x * 10;
println!("inner: {x}");
}
println!("outer: {x}");
}Answer
inner: 20, then outer: 2. The inner shadow dies at the closing brace.
Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 2.3 — Temperature converter
Write functions c_to_f(c: f64) -> f64 and f_to_c(f: f64) -> f64, then print a table
from −40 °C to 100 °C in steps of 20, right-aligned with one decimal place.
Solution
fn c_to_f(c: f64) -> f64 { c * 9.0 / 5.0 + 32.0 }
fn f_to_c(f: f64) -> f64 { (f - 32.0) * 5.0 / 9.0 }
fn main() {
println!("{:>8} {:>8}", "C", "F");
let mut c = -40.0;
while c <= 100.0 {
println!("{:>8.1} {:>8.1}", c, c_to_f(c));
c += 20.0;
}
assert!((f_to_c(212.0) - 100.0).abs() < 1e-9);
}Note the float comparison uses a tolerance, never ==.
🟡 Exercise 2.4 — Safe arithmetic
Write fn safe_average(a: u32, b: u32) -> Option<u32> that returns None if a + b
would overflow. Test it with (u32::MAX, 1) and (10, 20).
Solution
fn safe_average(a: u32, b: u32) -> Option<u32> {
a.checked_add(b).map(|sum| sum / 2)
}
fn main() {
println!("{:?}", safe_average(10, 20)); // Some(15)
println!("{:?}", safe_average(u32::MAX, 1)); // None
}Bonus: the overflow-free trick is a / 2 + b / 2 + (a % 2 + b % 2) / 2.
🟡 Exercise 2.5 — Tuple statistics
Write fn stats(data: [f64; 5]) -> (f64, f64, f64) returning (min, max, mean). Destructure
the result at the call site.
Solution
fn stats(data: [f64; 5]) -> (f64, f64, f64) {
let mut min = data[0];
let mut max = data[0];
let mut sum = 0.0;
for v in data {
if v < min { min = v; }
if v > max { max = v; }
sum += v;
}
(min, max, sum / data.len() as f64)
}
fn main() {
let (min, max, mean) = stats([3.0, 1.5, 9.25, -2.0, 4.0]);
println!("min={min} max={max} mean={mean:.3}");
}Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 2.6 — Overflow behaviour lab
Write a program that, for u8, prints the results of wrapping_add, checked_add,
saturating_add, and overflowing_add on 250 + 10. Then explain in comments which one
you'd use for: a cyclic buffer index, a bank balance, a progress percentage.
Solution
fn main() {
let a: u8 = 250;
println!("{}", a.wrapping_add(10)); // 4
println!("{:?}", a.checked_add(10)); // None
println!("{}", a.saturating_add(10)); // 255
println!("{:?}", a.overflowing_add(10)); // (4, true)
// cyclic buffer index -> wrapping_add (wrapping IS the semantics)
// bank balance -> checked_add (must never silently corrupt money)
// progress percentage -> saturating_add (clamp at 100, never exceed)
}Self-check
- Give two things shadowing can do that
mutcannot. - What is the size of a
charin Rust, and why isn't it 1 byte? - What happens on
u8overflow in debug vs release? - Why can't you call
.sort()onVec<f64>? - What three words make up a
Stringon the stack?
Answers
- Change the type of the value bound to a name; and produce a new immutable binding.
- 4 bytes — it holds a Unicode scalar value up to
U+10FFFF, not a byte. - Panics in debug; wraps silently in release.
f64has NaN, so it implementsPartialOrdbut notOrd;sortrequiresOrd.- Pointer to heap data, length, capacity.
