Logo

Developer learning path

Rust

Trait Objects in Rust

Trait Objects

57

#description

Trait objects are a fundamental concept in Rust programming that allow for dynamic dispatch of methods. When you specify a trait object, you are actually creating a pointer to an object whose type implements that trait.

In a Rust program, you can define a set of methods using a trait. These methods can then be implemented by any number of different types. When an object that implements the trait is created, it is guaranteed to have all of the methods defined by the trait.

Trait objects allow for a kind of dynamic polymorphism in Rust. Because Rust is a statically typed language, the types of objects are checked at compile time. But with trait objects, the type of an object can be determined at runtime, allowing for runtime polymorphism.

To create a trait object, you would declare your trait as follows:

                    
trait MyTrait {
    fn my_method(&self);
}
                  

And then implement the trait for a particular type:

                    
struct MyType;

impl MyTrait for MyType {
    fn my_method(&self) {
        println!("This is a method on MyType");
    }
}
                  

Once you've implemented the trait for a type, you can create a trait object that points to any object that implements the trait:

                    
fn main() {
    let my_type = MyType;
    let my_trait_object: &dyn MyTrait = &my_type;
    my_trait_object.my_method();
}
                  

In this example, we're creating a trait object that points to my_type. We can then call my_method() on the trait object and it will dynamically dispatch the method to the implementation on MyType.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.