Logo

Developer learning path

Rust

Defining Traits in Rust

Defining Traits

40

#description

In Rust, traits are a way to define a set of functionality that a type can implement. They provide a way to define methods that can be implemented on any type, similar to interfaces in other programming languages.

A trait defines a set of method signatures that a type must implement in order to satisfy the requirements of that trait. When a type does implement a trait, it is said to "implement" that trait. This allows other code to interact with the type in a generic way, regardless of the specific type that is being used.

For example, let's say we have two types: Dog and Cat. Both of these types could implement a Pet trait that defines methods like pet_name(), speak(), and play(). By implementing the Pet trait, these types can be used in a generic way by any code that relies on that trait, allowing us to write more generic and reusable code.

We can define our own traits in Rust by using the trait keyword, followed by a set of method signatures.

Here's an example:

                    
trait Pet {
    fn pet_name(&self) -> String;
    fn speak(&self);
    fn play(&self);
}
                  

This defines a Pet trait with three method signatures: pet_name(), speak(), and play().

To implement this trait for a specific type, we would define an implementation block like this:

                    
struct Dog {
    name: String,
}

impl Pet for Dog {
    fn pet_name(&self) -> String {
        self.name.clone()
    }
    fn speak(&self) {
        println!("Woof!");
    }
    fn play(&self) {
        println!("Fetch the ball!");
    }
}
                  

This defines a Dog struct with a name field, and an implementation of the Pet trait for that struct. We provide implementations for each of the required methods (pet_name(), speak(), and play()), and can now use this type in a generic way wherever the Pet trait is required.

Traits are a powerful feature of Rust that allow us to define generic functionality and write more reusable code. By defining traits and implementing them for our types, we can take advantage of Rust's powerful type system and make our code more expressive 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.