Rust Tutorial: Traits
Define shared behaviour with traits, implement them for your types, and use trait bounds.
Shared behaviour
A trait defines behaviour that types can share. It is Rust's equivalent of interfaces in other languages — but more powerful.
What you'll learn in this Rust traits tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 20 minutes.
- Define a trait — A trait declares method signatures. Types implement them.
- Default methods — Trait methods can have default implementations that types can override.
- Trait bounds — Use traits as constraints on generics: `fn foo<T: Trait>(x: T)`
- Multiple trait bounds — Require multiple traits with `+`:
- Implement Display — Implement `std::fmt::Display` to control how your type prints with `{}`.
- where clause — For complex bounds, use a `where` clause for readability:
- Trait objects with dyn — `dyn Trait` is a runtime-dispatched trait object. Use when you need a collection of different types.
- Derive common traits — Use `#[derive]` to auto-implement common traits.
Rust Traits concepts covered
- Shared behaviour