7 Traits: Making different types do the same thing
This chapter covers
- The basics - How to write your own traits
- Method signatures in traits
- More complex trait examples
- The From trait
- The orphan rule - what you're allowed to implement a trait on
- Taking a String or a &str in a function
We’ve worked with traits already but now it’s time to understand them better so we can implement traits made by others and make our own.
We have seen traits before: Debug, Copy, Clone are all traits. The easiest way to think of traits is as “powers”. If a type has a trait, it can do things it couldn't do before. Also, if a type has a trait then you can guarantee to the compiler that it can do something - no matter what type it is.
To give a trait to a type, you have to implement that trait for that type. "Type X implements Trait Y" means that Type X definitely has the methods that Trait Y gives to Type X. Type X might have its own methods too, and Type X might implement other traits as well.
Rust has attributes to automatically implement traits like Debug, because they are so common. That's what happens when you write #[derive(Debug)]: you are automatically implementing Debug. So all you need to do is this:
#[derive(Debug)]
struct MyStruct {
number: usize,
}
fn main() {}