Skip to content
RustLearn

Module 11 Exercises — Generics

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 explain:

  • what <T> means when you see it in a signature;
  • what a trait bound is for, in terms of what the function body needs to do;
  • why generics in Rust cost nothing at runtime, and what they cost instead.

A good technique for every drill here: write the generic version with no bounds first, compile, and let the error tell you which bound to add. It is faster than reasoning it out, and you learn the trait names in the process.

Part A — Warm-Up Drills

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

🟢 Exercise 11.1 — Generic largest with owned return

Rewrite largest to return T by value instead of &T. What bound do you now need, and why?

Solution
rust
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];
    for &item in list {
        if item > largest { largest = item; }
    }
    largest
}

You need Copy (or Clone plus explicit cloning) because you can't move a value out of a borrowed slice. This is why the standard library's version returns a reference — it works for String too.

🟢 Exercise 11.2 — Generic swap and pair

Write fn swap<T>(pair: (T, T)) -> (T, T) and struct Wrapper<T>(T) with methods get(&self) -> &T and into_inner(self) -> T.

Solution
rust
fn swap<T>(pair: (T, T)) -> (T, T) { (pair.1, pair.0) }

struct Wrapper<T>(T);

impl<T> Wrapper<T> {
    fn new(v: T) -> Self { Wrapper(v) }
    fn get(&self) -> &T { &self.0 }
    fn into_inner(self) -> T { self.0 }
}

fn main() {
    println!("{:?}", swap((1, 2)));
    let w = Wrapper::new(String::from("hi"));
    println!("{}", w.get());
    let s: String = w.into_inner();
    println!("{s}");
}

Notice neither needs any bound — they only move values around.

Part B — Core Exercises

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

🟡 Exercise 11.3 — Generic Stack

Implement struct Stack<T> { items: Vec<T> } with new, push, pop, peek, is_empty, len. Then add fn contains(&self, x: &T) -> bool — and note which bound that requires.

Solution
rust
#[derive(Debug, Default)]
struct Stack<T> { items: Vec<T> }

impl<T> Stack<T> {
    fn new() -> Self { Stack { items: Vec::new() } }
    fn push(&mut self, item: T) { self.items.push(item); }
    fn pop(&mut self) -> Option<T> { self.items.pop() }
    fn peek(&self) -> Option<&T> { self.items.last() }
    fn is_empty(&self) -> bool { self.items.is_empty() }
    fn len(&self) -> usize { self.items.len() }
}

impl<T: PartialEq> Stack<T> {
    fn contains(&self, x: &T) -> bool { self.items.iter().any(|i| i == x) }
}

fn main() {
    let mut s: Stack<i32> = Stack::new();
    s.push(1); s.push(2); s.push(3);
    assert_eq!(s.peek(), Some(&3));
    assert!(s.contains(&2));
    assert_eq!(s.pop(), Some(3));
    assert_eq!(s.len(), 2);

    let mut words: Stack<String> = Stack::new();
    words.push("hello".into());
    assert!(words.contains(&"hello".to_string()));
}

contains needs PartialEq, so it goes in its own impl block — Stack<T> for non-comparable T still gets everything else.

🟡 Exercise 11.4 — Generic function with multiple bounds

Write fn describe_all<T>(items: &[T]) -> String where T: Display + PartialOrd that returns "3 items, min=1, max=9". Use a where clause.

Solution
rust
use std::fmt::Display;

fn describe_all<T>(items: &[T]) -> String
where
    T: Display + PartialOrd,
{
    if items.is_empty() { return "0 items".to_string(); }
    let mut min = &items[0];
    let mut max = &items[0];
    for item in items {
        if item < min { min = item; }
        if item > max { max = item; }
    }
    format!("{} items, min={min}, max={max}", items.len())
}

fn main() {
    println!("{}", describe_all(&[3, 1, 9, 4]));
    println!("{}", describe_all(&["pear", "apple", "quince"]));
}

Part C — Challenges

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

🔴 Exercise 11.5 — Generic binary search tree

Implement struct Bst<T: Ord> { root: Option<Box<Node<T>>> } with insert, contains, and in_order(&self) -> Vec<&T>. Test with integers and with Strings.

Solution
rust
#[derive(Debug)]
struct Node<T> { value: T, left: Option<Box<Node<T>>>, right: Option<Box<Node<T>>> }

#[derive(Debug, Default)]
struct Bst<T: Ord> { root: Option<Box<Node<T>>> }

impl<T: Ord> Bst<T> {
    fn new() -> Self { Bst { root: None } }

    fn insert(&mut self, value: T) {
        let mut cur = &mut self.root;
        while let Some(node) = cur {
            cur = if value < node.value { &mut node.left } else { &mut node.right };
        }
        *cur = Some(Box::new(Node { value, left: None, right: None }));
    }

    fn contains(&self, value: &T) -> bool {
        let mut cur = &self.root;
        while let Some(node) = cur {
            if *value == node.value { return true; }
            cur = if *value < node.value { &node.left } else { &node.right };
        }
        false
    }

    fn in_order(&self) -> Vec<&T> {
        fn walk<'a, T: Ord>(n: &'a Option<Box<Node<T>>>, out: &mut Vec<&'a T>) {
            if let Some(node) = n {
                walk(&node.left, out);
                out.push(&node.value);
                walk(&node.right, out);
            }
        }
        let mut out = Vec::new();
        walk(&self.root, &mut out);
        out
    }
}

fn main() {
    let mut t = Bst::new();
    for v in [5, 3, 8, 1, 4, 7, 9] { t.insert(v); }
    assert_eq!(t.in_order(), vec![&1, &3, &4, &5, &7, &8, &9]);
    assert!(t.contains(&7));
    assert!(!t.contains(&6));

    let mut words = Bst::new();
    for w in ["pear", "apple", "quince"] { words.insert(w.to_string()); }
    println!("{:?}", words.in_order());
}

The iterative insert walking &mut Option<Box<Node<T>>> is worth studying — it's the canonical way to mutate a linked structure without fighting the borrow checker. Each loop iteration replaces the mutable borrow rather than nesting it.

Self-check

  1. What is monomorphization, and what are its two costs?
  2. When must you use where instead of inline bounds?
  3. Why can't fn f() -> impl Trait return two different concrete types?
  4. How do you give a method to Point<T> only when T: Display?
  5. Name two situations where you should reach for dyn Trait instead of a generic.
Answers
  1. Generating a specialized copy of generic code per concrete type. Costs: bigger binaries and slower compilation.
  2. Never strictly required, but necessary for readability with multiple parameters/bounds, and required for some bounds on associated types.
  3. Because impl Trait is a single opaque concrete type chosen at compile time.
  4. Put it in a separate impl<T: Display> Point<T> { ... } block.
  5. Heterogeneous collections, and types chosen at runtime (also: cutting compile times).

Next: Module 12 — Traits & Trait Objects