Module 06 Exercises — Structs & Methods
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 say without hesitating:
- when a method should take
&selfrather thanself; - what the difference is between
Rectangle::new(..)andrect.area(); - why
#[derive(Debug)]exists and when you need it.
If a drill fails with "doesn't implement Debug", that is not a mistake to fix and forget — it is the compiler showing you that behaviours in Rust are opt-in. Add the derive and note why it was needed.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 6.1 — Rectangle basics
Define Rectangle with width and height, plus area, perimeter, is_square, and
an associated square(size) constructor. Print with {:#?}.
Solution
#[derive(Debug)]
struct Rectangle { width: f64, height: f64 }
impl Rectangle {
fn square(size: f64) -> Self { Self { width: size, height: size } }
fn area(&self) -> f64 { self.width * self.height }
fn perimeter(&self) -> f64 { 2.0 * (self.width + self.height) }
fn is_square(&self) -> bool { (self.width - self.height).abs() < f64::EPSILON }
}
fn main() {
let r = Rectangle { width: 3.0, height: 4.0 };
println!("{r:#?} area={} perim={} square={}", r.area(), r.perimeter(), r.is_square());
println!("{:?}", Rectangle::square(5.0));
}🟢 Exercise 6.2 — Receiver choice
For each method, decide self, &self, or &mut self:
len, push, into_iter, clear, is_empty, into_string, sort.
Answers
len &self; push &mut self; into_iter self; clear &mut self;
is_empty &self; into_string self; sort &mut self.
Naming convention: into_* takes self, as_* takes &self, to_* takes &self and
allocates.
Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 6.3 — Bank account with invariants
Write struct Account { owner: String, balance_cents: i64 } with:
new(owner) -> Selfstarting at 0deposit(&mut self, cents: u64)withdraw(&mut self, cents: u64) -> bool— returns false and changes nothing if funds are insufficientbalance(&self) -> f64in dollarsDisplayprintingAda: $12.34
Solution
use std::fmt;
struct Account { owner: String, balance_cents: i64 }
impl Account {
fn new(owner: impl Into<String>) -> Self {
Self { owner: owner.into(), balance_cents: 0 }
}
fn deposit(&mut self, cents: u64) {
self.balance_cents += cents as i64;
}
fn withdraw(&mut self, cents: u64) -> bool {
let c = cents as i64;
if self.balance_cents >= c { self.balance_cents -= c; true } else { false }
}
fn balance(&self) -> f64 { self.balance_cents as f64 / 100.0 }
}
impl fmt::Display for Account {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: ${:.2}", self.owner, self.balance())
}
}
fn main() {
let mut a = Account::new("Ada");
a.deposit(1234);
assert!(!a.withdraw(9999));
println!("{a}"); // Ada: $12.34
}Money is stored in integer cents, never floats — a habit worth forming.
🟡 Exercise 6.4 — Newtype validation
Write struct Email(String) with a private field and fn parse(s: &str) -> Option<Email>
that accepts only strings containing exactly one @ with non-empty parts. Add
fn domain(&self) -> &str.
Solution
#[derive(Debug, Clone, PartialEq)]
pub struct Email(String);
impl Email {
pub fn parse(s: &str) -> Option<Email> {
let mut parts = s.split('@');
let (local, domain) = (parts.next()?, parts.next()?);
if parts.next().is_some() || local.is_empty() || domain.is_empty() {
return None;
}
Some(Email(s.to_string()))
}
pub fn domain(&self) -> &str {
self.0.split('@').nth(1).unwrap() // safe: validated at construction
}
}
fn main() {
let e = Email::parse("ada@rust-lang.org").unwrap();
assert_eq!(e.domain(), "rust-lang.org");
assert!(Email::parse("nope").is_none());
assert!(Email::parse("a@b@c").is_none());
}Because the field is private, no one outside the module can construct an invalid Email.
This is "parse, don't validate": the type itself carries the proof.
Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 6.5 — Matrix type
Implement struct Matrix { rows: usize, cols: usize, data: Vec<f64> } (row-major) with:
new(rows, cols) zeroed, identity(n), get(r, c) -> Option<f64>,
set(&mut self, r, c, v), transpose(&self) -> Matrix,
multiply(&self, other: &Matrix) -> Option<Matrix>, and Display printing aligned rows.
Solution
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
struct Matrix { rows: usize, cols: usize, data: Vec<f64> }
impl Matrix {
fn new(rows: usize, cols: usize) -> Self {
Self { rows, cols, data: vec![0.0; rows * cols] }
}
fn identity(n: usize) -> Self {
let mut m = Self::new(n, n);
for i in 0..n { m.set(i, i, 1.0); }
m
}
fn idx(&self, r: usize, c: usize) -> usize { r * self.cols + c }
fn get(&self, r: usize, c: usize) -> Option<f64> {
if r < self.rows && c < self.cols { Some(self.data[self.idx(r, c)]) } else { None }
}
fn set(&mut self, r: usize, c: usize, v: f64) {
let i = self.idx(r, c);
self.data[i] = v;
}
fn transpose(&self) -> Matrix {
let mut t = Matrix::new(self.cols, self.rows);
for r in 0..self.rows {
for c in 0..self.cols {
t.set(c, r, self.get(r, c).unwrap());
}
}
t
}
fn multiply(&self, other: &Matrix) -> Option<Matrix> {
if self.cols != other.rows { return None; }
let mut out = Matrix::new(self.rows, other.cols);
for i in 0..self.rows {
for j in 0..other.cols {
let mut acc = 0.0;
for k in 0..self.cols {
acc += self.get(i, k)? * other.get(k, j)?;
}
out.set(i, j, acc);
}
}
Some(out)
}
}
impl fmt::Display for Matrix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for r in 0..self.rows {
for c in 0..self.cols {
write!(f, "{:>8.2}", self.get(r, c).unwrap())?;
}
writeln!(f)?;
}
Ok(())
}
}
fn main() {
let mut a = Matrix::new(2, 3);
for (i, v) in (1..=6).enumerate() { a.data[i] = v as f64; }
println!("{a}");
println!("{}", a.transpose());
let i3 = Matrix::identity(3);
assert_eq!(a.multiply(&i3).unwrap(), a);
}Note the ? inside Display::fmt — write! returns a Result and every write must be
propagated. That's module 08 material appearing naturally.
Self-check
- What's the difference between
Rectangle::new(..)andrect.area()syntactically and semantically? - When does
..otherin struct update syntax move data? - Why is
Displaynot derivable whenDebugis? - What does the newtype pattern cost at runtime?
- Which derive requires that all fields also implement it, and additionally requires
Clone?
Answers
::calls an associated function with no receiver;.calls a method with an automatically-referencedself.- Whenever the borrowed-from fields are not
Copy— those fields are moved out. Debugis for programmers and can be mechanically generated;Displayis user-facing presentation, which the compiler can't guess.- Nothing — it's a compile-time-only wrapper with identical layout.
Copy.
