Introduction
Traits are a way of describing a 'contract' that a struct
must implement. Traits typically define method signatures but can also provide implementations based on other methods of the trait, providing the trait bounds allow for this.
For those familiar with object oriented programming, traits can be thought of as interfaces with some subtle differences.
Syntax
- trait Trait { fn method(...) -> ReturnType; ... }
- trait Trait: Bound { fn method(...) -> ReturnType; ... }
- impl Trait for Type { fn method(...) -> ReturnType { ... } ... }
- impl<T> Trait for T where T: Bounds { fn method(...) -> ReturnType { ... } ... }
- Traits are commonly likened to interfaces, but it is important to make a distinction between the two. In OO languages like Java, interfaces are an integral part of the classes that extend them. In Rust, the compiler knows nothing of a struct's traits unless those traits are used.