Rust Tutorial: Traits in Rust
Define shared behavior with traits and implement them for types.
Concepts in this chapter
You will learn and practice:
- **trait** — define a set of methods; like an interface
- **impl Trait for Type** — implement the trait for your struct
- **Default implementations** — methods in the trait with a body
- **Trait bounds** — generic functions that require T: Trait
- **derive** — #[derive(Debug, Clone)] for common traits
---
Defining and Implementing a Trait
```rust
trait Greet {
fn greet(&self) -> String;
}
struct Person;
impl Greet for Person {
fn greet(&self) -> String {
"Hello!".to_string()
}
}
fn main() {
let p = Person;
println!("{}", p.greet());
}
```
---
What's Next?
Next: **Error Handling with Result** — Result and ? operator.
What you'll learn in this Rust traits in rust tutorial
This interactive Rust tutorial has 2 hands-on exercises. Estimated time: 15 minutes.
- Implement a Trait — Define a trait Greet with one method fn greet(&self) -> String. Create a struct EnglishGreeter and impl Greet for it ret…
- Trait and Polymorphism — Have a trait Sound with fn make_sound(&self) -> &str. Dog returns "Woof", Cat returns "Meow". In main, put a Dog and Cat…
Rust Traits in Rust concepts covered
- Concepts in this chapter
- Defining and Implementing a Trait
- What's Next?