Skip to content
RustLearn

Module 12 Exercises — Traits & Trait Objects

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, make sure you can:

  • explain why traits are not inheritance, in one sentence;
  • decide between impl Trait and Box<dyn Trait> for a given situation;
  • name three standard traits and what implementing each one gives you.

If a drill fights you on the orphan rule, that is the module doing its job — the newtype wrapper is the intended answer, and it is a pattern you will use in real projects.

Part A — Warm-Up Drills

Short reps on the mechanics. Do them until the syntax stops costing you any thought.

🟢 Exercise 12.1 — Trait with a default method

Define trait Greet { fn name(&self) -> String; fn greet(&self) -> String { ... } } and implement it for two structs, overriding greet in one.

Solution
rust
trait Greet {
    fn name(&self) -> String;
    fn greet(&self) -> String { format!("Hello, {}!", self.name()) }
}

struct Person(String);
struct Robot(u32);

impl Greet for Person { fn name(&self) -> String { self.0.clone() } }
impl Greet for Robot {
    fn name(&self) -> String { format!("Unit-{}", self.0) }
    fn greet(&self) -> String { format!("BEEP. {} ONLINE.", self.name()) }
}

fn main() {
    println!("{}", Person("Ada".into()).greet());
    println!("{}", Robot(7).greet());
}

🟢 Exercise 12.2 — Display and Debug

Implement Display for a Duration { secs: u64 } printing "1h 23m 45s" (omitting zero units), while deriving Debug. Print both with {} and {:?}.

Solution
rust
use std::fmt;

#[derive(Debug)]
struct Duration { secs: u64 }

impl fmt::Display for Duration {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let (h, m, s) = (self.secs / 3600, (self.secs % 3600) / 60, self.secs % 60);
        let mut parts = Vec::new();
        if h > 0 { parts.push(format!("{h}h")); }
        if m > 0 { parts.push(format!("{m}m")); }
        if s > 0 || parts.is_empty() { parts.push(format!("{s}s")); }
        write!(f, "{}", parts.join(" "))
    }
}

fn main() {
    let d = Duration { secs: 5025 };
    println!("{d} / {d:?}");        // 1h 23m 45s / Duration { secs: 5025 }
    println!("{}", Duration { secs: 0 });   // 0s
}

Part B — Core Exercises

The real practice. Attempt each one fully — compiler errors included — before opening a solution.

🟡 Exercise 12.3 — Static vs dynamic dispatch

Write trait Shape { fn area(&self) -> f64; fn name(&self) -> &str; } with Circle, Square, Triangle. Then write:

  1. fn print_area<T: Shape>(s: &T) (static)
  2. fn total_area(shapes: &[Box<dyn Shape>]) -> f64 (dynamic)
  3. fn largest(shapes: &[Box<dyn Shape>]) -> Option<&dyn Shape>
Solution
rust
trait Shape {
    fn area(&self) -> f64;
    fn name(&self) -> &str;
}

struct Circle(f64);
struct Square(f64);
struct Triangle { base: f64, height: f64 }

impl Shape for Circle {
    fn area(&self) -> f64 { std::f64::consts::PI * self.0 * self.0 }
    fn name(&self) -> &str { "circle" }
}
impl Shape for Square {
    fn area(&self) -> f64 { self.0 * self.0 }
    fn name(&self) -> &str { "square" }
}
impl Shape for Triangle {
    fn area(&self) -> f64 { 0.5 * self.base * self.height }
    fn name(&self) -> &str { "triangle" }
}

fn print_area<T: Shape>(s: &T) { println!("{}: {:.2}", s.name(), s.area()); }

fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
    shapes.iter().map(|s| s.area()).sum()
}

fn largest(shapes: &[Box<dyn Shape>]) -> Option<&dyn Shape> {
    shapes.iter()
        .max_by(|a, b| a.area().partial_cmp(&b.area()).unwrap())
        .map(|b| b.as_ref())
}

fn main() {
    print_area(&Circle(1.0));
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle(1.0)),
        Box::new(Square(2.0)),
        Box::new(Triangle { base: 3.0, height: 4.0 }),
    ];
    println!("total {:.2}", total_area(&shapes));
    println!("largest {}", largest(&shapes).unwrap().name());
}

Note partial_cmp — f64 isn't Ord, so max_by_key won't work directly.

🟡 Exercise 12.4 — Operator overloading

Implement a Vector2 { x: f64, y: f64 } with Add, Sub, Mul<f64> (scalar), Neg, AddAssign, and Display as (1.0, 2.0). Add a dot and magnitude method.

Solution
rust
use std::fmt;
use std::ops::{Add, AddAssign, Mul, Neg, Sub};

#[derive(Debug, Clone, Copy, PartialEq)]
struct Vector2 { x: f64, y: f64 }

impl Vector2 {
    fn new(x: f64, y: f64) -> Self { Self { x, y } }
    fn dot(self, o: Self) -> f64 { self.x * o.x + self.y * o.y }
    fn magnitude(self) -> f64 { self.dot(self).sqrt() }
}

impl Add for Vector2 { type Output = Self;
    fn add(self, o: Self) -> Self { Self::new(self.x + o.x, self.y + o.y) } }
impl Sub for Vector2 { type Output = Self;
    fn sub(self, o: Self) -> Self { Self::new(self.x - o.x, self.y - o.y) } }
impl Mul<f64> for Vector2 { type Output = Self;
    fn mul(self, k: f64) -> Self { Self::new(self.x * k, self.y * k) } }
impl Neg for Vector2 { type Output = Self;
    fn neg(self) -> Self { Self::new(-self.x, -self.y) } }
impl AddAssign for Vector2 {
    fn add_assign(&mut self, o: Self) { self.x += o.x; self.y += o.y; } }
impl fmt::Display for Vector2 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y) } }

fn main() {
    let mut a = Vector2::new(3.0, 4.0);
    println!("{}", a.magnitude());          // 5
    println!("{}", a + Vector2::new(1.0, 1.0));
    println!("{}", -a * 2.0);
    a += Vector2::new(1.0, 1.0);
    println!("{a}");
}

Part C — Challenges

Longer builds. Expect to fight the borrow checker here; that fight is the lesson.

🔴 Exercise 12.5 — Plugin system

Build a small plugin architecture:

  • trait Plugin { fn name(&self) -> &str; fn execute(&self, input: &str) -> String; }
  • struct Registry { plugins: HashMap<String, Box<dyn Plugin>> } with register and run(&self, name, input) -> Option<String>
  • Three plugins: Upper, Reverse, WordCount
  • A pipeline(&self, names: &[&str], input: &str) -> Result<String, String> that chains plugins and errors on an unknown name
Solution
rust
use std::collections::HashMap;

trait Plugin {
    fn name(&self) -> &str;
    fn execute(&self, input: &str) -> String;
}

struct Upper;
struct Reverse;
struct WordCount;

impl Plugin for Upper {
    fn name(&self) -> &str { "upper" }
    fn execute(&self, i: &str) -> String { i.to_uppercase() }
}
impl Plugin for Reverse {
    fn name(&self) -> &str { "reverse" }
    fn execute(&self, i: &str) -> String { i.chars().rev().collect() }
}
impl Plugin for WordCount {
    fn name(&self) -> &str { "wordcount" }
    fn execute(&self, i: &str) -> String { i.split_whitespace().count().to_string() }
}

#[derive(Default)]
struct Registry { plugins: HashMap<String, Box<dyn Plugin>> }

impl Registry {
    fn register(&mut self, p: Box<dyn Plugin>) {
        self.plugins.insert(p.name().to_string(), p);
    }
    fn run(&self, name: &str, input: &str) -> Option<String> {
        self.plugins.get(name).map(|p| p.execute(input))
    }
    fn pipeline(&self, names: &[&str], input: &str) -> Result<String, String> {
        let mut cur = input.to_string();
        for n in names {
            cur = self.run(n, &cur).ok_or_else(|| format!("unknown plugin: {n}"))?;
        }
        Ok(cur)
    }
}

fn main() {
    let mut reg = Registry::default();
    reg.register(Box::new(Upper));
    reg.register(Box::new(Reverse));
    reg.register(Box::new(WordCount));

    println!("{:?}", reg.pipeline(&["upper", "reverse"], "hello world"));
    println!("{:?}", reg.pipeline(&["wordcount"], "a b c"));
    println!("{:?}", reg.pipeline(&["nope"], "x"));
}

This is the canonical case where dyn Trait is right: the set of plugins is known only at runtime, and they must live in one collection.

Self-check

  1. What does the orphan rule prevent, and how do you work around it?
  2. Give two reasons a trait might not be object safe.
  3. When do you choose an associated type over a generic trait parameter?
  4. Why implement From rather than Into?
  5. What are the two words in a &dyn Trait fat pointer?
Answers
  1. It prevents conflicting implementations of a trait for a type across crates; work around it with the newtype pattern.
  2. It returns Self, or it has generic methods (or requires Self: Sized).
  3. When the implementing type determines the type (one obvious choice per impl).
  4. A blanket impl gives you Into automatically, and From composes better with ? and inference.
  5. A pointer to the data and a pointer to the vtable.

Next: Module 13 — Lifetimes