Logo

Developer learning path

Rust

Traits in Rust

Traits

54

#description

In Rust, traits are a way of defining a set of behaviors or capabilities that can be implemented by types. Traits are similar to interfaces in other languages, but they have additional features that make them even more powerful.

A trait is defined using the trait keyword, followed by the name of the trait and a set of method signatures or associated types that define the behavior of the trait.

Here is an example trait that defines a Drawable behavior:

                    
trait Drawable {
    fn draw(&self);
}
                  

Any type that implements the Drawable trait must implement the draw method, which takes a reference to self.

To implement a trait for a type, you use the impl keyword followed by the name of the trait and the type you are implementing it for.

For example, here is how you might implement the Drawable trait for a Rectangle struct:

                    
struct Rectangle {
    width: u32,
    height: u32,
}

impl Drawable for Rectangle {
    fn draw(&self) {
        // do drawing here
    }
}
                  

Now, any code that requires a Drawable object can use a Rectangle object, since it implements the Drawable trait. This allows for more flexible and reusable code.

Traits can also have associated types, which are types that are defined by the trait but can be implemented differently by each type that implements the trait. This allows for even more flexibility and generic programming.

In summary, traits are a powerful feature of Rust that allow you to define sets of behaviors that can be implemented by different types, making your code more reusable and flexible.

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.