Skip to content
Learn Netverks

Lesson

Step 26/36 72% through track

trait-objects

Trait objects

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
advanced

This lesson

This lesson teaches Trait objects: the syntax, APIs, and habits you need before advancing in Rust.

Traits are Rust’s abstraction for shared behavior—like interfaces plus generics, enforced at compile time.

You will apply Trait objects in contexts like: Infrastructure CLIs, proxies, game engines, blockchain nodes, and latency-sensitive backends.

Write Rust with fn main(), click Run on server—the dev runner compiles main.rs with rustc and runs the binary; fix borrow errors from stderr (requires Rust toolchain; LEARNING_RUNNER_ENABLED=true).

When functions, arrays, and basic OOP from intermediate lessons are familiar.

Trait objects dyn Trait enable dynamic dispatch—store different types behind one pointer when sizes differ. Trade runtime vtable cost for flexibility.

Example

let shapes: Vec<Box<dyn Drawable>> = vec![...];

Important interview questions and answers

  1. Q: dyn Trait vs generic bound?
    A: Generics static dispatch at compile time; trait objects dynamic dispatch at runtime.

Self-check

  1. What does Box<dyn Trait> enable?
  2. When prefer generics over trait objects?

Interview prep

dyn Trait vs generics?

Generics use static dispatch at compile time; dyn Trait uses dynamic dispatch at runtime via vtables.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • dyn Trait when?
  • Object safety?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump