A trait implementation declares that a type provides a trait’s behavior. Unlike inheritance, traits connect types through the capabilities they implement; a trait can apply to different types, subject to any required trait bounds. section 2.2.2 section 2.2
trait DoesItBark { #1
fn it_barks(&self) -> bool; #2
}
struct Dog;
impl DoesItBark for Dog { #3
fn it_barks(&self) -> bool {
true #4
}
}
A minimal example defines a barking capability and implements it for Dog by supplying the required method. section 2.2.2
Choose how to provide the implementation:
- Use #[derive] for supported common traits such as Clone, Debug, and Default; it supplies implementations with little boilerplate. section 2.2.5
- Write an impl yourself when the behavior should differ from the derived default. For example, a custom Default implementation can create a Pumpkin with chosen field values. section 2.2.5
- Rust does not allow implementing a trait for a type outside your crate; this restriction prevents conflicting implementations from different crates. section 7.2
