Skip to content
← All Rust tracks

Trait Objects and Dispatch

Rust

Work with values of different concrete types through shared interfaces. Compare generics, trait objects and enums, including their ownership and dispatch tradeoffs.

This track uses Rust. You can make it your practice mode to browse related content across the site.

7 exercises

3 articles

Explore freely. Sign in to keep your progress.

Your learning sequence

  1. 1 Not solved yet. Box<dyn Trait>: trait objects, DSTs and dynamic dispatch Practice · Medium
  2. 2 Not solved yet. Keep concrete methods while enabling trait objects Practice · Hard
  3. 3 Not solved yet. Static vs dynamic dispatch Practice · Hard
  4. 4 Not solved yet. Delegate shape methods through an enum Practice · Medium
  5. 5 Choosing between generics, impl Trait, &dyn, Box<dyn> and enums Read
  6. 6 Monomorphisation: what generics compile to, and what that costs Read
  7. 7 Not solved yet. Dispatch through Rc: Rc<dyn Trait> and shared behaviour Practice · Medium
  8. 8 Not solved yet. Trait objects and lifetimes: Box<dyn Trait + 'a> Practice · Hard
  9. 9 async fn in traits and RPITIT: what works and what does not Read
  10. 10 Not solved yet. Choose parameter types and shrink an enum Practice · Medium

Check yourself

4 questions · not saved while you're signed out

Use these questions to check your understanding and compare explanations. Your score does not affect track completion.

0 / 4 correct

How does this vector hold both Circle and Square values behind one interface?

Choose one answer to reveal the explanations. Answers are kept only while this page is open.

trait Shape {
    fn name(&self) -> &'static str;
}
struct Circle;
struct Square;
impl Shape for Circle {
    fn name(&self) -> &'static str { "circle" }
}
impl Shape for Square {
    fn name(&self) -> &'static str { "square" }
}

fn main() {
    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle), Box::new(Square)];
    for shape in shapes {
        println!("{}", shape.name());
    }
}
Question 1 of 4