codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🦀

Rust

34 / 58 topics
32Generics33Traits34Trait Objects
Tutorials/Rust/Trait Objects
🦀Rust

Trait Objects

Updated 2026-05-15
10 min read

Trait Objects

Introduction

In Rust, traits are a powerful feature that allows you to define shared behavior across different types. When you use a trait object, you can store references to values of any type that implements the trait, enabling dynamic dispatch. This means that the method to be called is determined at runtime, which provides flexibility and polymorphism.

Trait objects are particularly useful when you need to handle multiple types with a common interface but don't know the exact types at compile time. They allow you to write more generic code that can work with any type that implements a specific trait.

Concept

A trait object is represented by the syntax dyn Trait, where Trait is the name of the trait. When you use a trait object, Rust uses dynamic dispatch to determine which method implementation to call at runtime. This involves some overhead compared to static dispatch, but it provides the flexibility needed for certain scenarios.

To create a trait object, you need to ensure that the trait has an 'static lifetime bound and is Sized. The 'static lifetime ensures that the trait object can be safely used across different scopes without worrying about lifetimes. The Sized requirement ensures that the size of the trait object is known at compile time.

Examples

Let's look at some examples to understand how trait objects work in Rust.

Basic Trait Object Example

First, let's define a simple trait and implement it for two different types:

Rust
1trait Animal {
2 fn make_sound(&self);
3}
4
5struct Dog;
6struct Cat;
7
8impl Animal for Dog {
9 fn make_sound(&self) {
10 println!("Woof!");
11 }
12}
13
14impl Animal for Cat {
15 fn make_sound(&self) {
16 println!("Meow!");
17 }
18}

Now, let's create a function that takes a trait object and calls its make_sound method:

Rust
1fn animal_sounds(animals: Vec<Box<dyn Animal>>) {
2 for animal in animals {
3 animal.make_sound();
4 }
5}
6
7fn main() {
8 let dog = Box::new(Dog);
9 let cat = Box::new(Cat);
10
11 let animals: Vec<Box<dyn Animal>> = vec![dog, cat];
12 animal_sounds(animals);
13}

In this example, we define a Vec of trait objects (Box<dyn Animal>) and pass it to the animal_sounds function. The function iterates over the vector and calls the make_sound method on each trait object. Since the type of each element in the vector is not known at compile time, Rust uses dynamic dispatch to determine which implementation of make_sound to call.

Using Trait Objects with Lifetimes

Trait objects can also be used with lifetimes. Here's an example that demonstrates how to use a trait object with a lifetime bound:

Rust
1trait Greet {
2 fn greet(&self) -> String;
3}
4
5struct Person<'a> {
6 name: &'a str,
7}
8
9impl<'a> Greet for Person<'a> {
10 fn greet(&self) -> String {
11 format!("Hello, {}!", self.name)
12 }
13}
14
15fn main() {
16 let person = Person { name: "Alice" };
17 let greeting: Box<dyn Greet + 'static> = Box::new(person);
18 println!("{}", greeting.greet());
19}

In this example, the Person struct has a lifetime parameter 'a, and the Greet trait implementation for Person also includes the lifetime bound. The trait object is created with a 'static lifetime bound to ensure that it can be safely used across different scopes.

What's Next?

In the next section, we will explore pattern matching in Rust. Pattern matching allows you to match values against patterns and execute code based on those matches. It is a powerful feature that enables you to write concise and expressive code.

Stay tuned for more tutorials on Rust!


PreviousTraitsNext Pattern Matching

Recommended Gear

TraitsPattern Matching