Rust Reference ยท Keywords and Statements
The trait keyword
Reference for Rust trait: required and provided methods, associated types and consts, supertraits, generic traits, object safety, unsafe traits and trait aliases.
A trait declares a set of methods, associated types and constants that a type can promise to provide. Generic code uses traits as bounds (T: Summary), and trait objects (dyn Summary) use them for dynamic dispatch.
A trait can supply default bodies for some methods, so implementors only write what is essential. Traits are Rust's tool for abstraction, comparable to interfaces in other languages but with associated types, blanket impls and static dispatch by default.
trait Summary { fn author(&self) -> String; fn summarize(&self) -> String { format!("(more from {}...)", self.author()) } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
[pub] [unsafe] trait Name<generics>: Supertrait + Other where bounds { type Assoc: Bound; const NAME: Type [= default]; fn required(&self, ...) -> Ret; fn provided(&self) -> Ret { body } }
| Part | Description |
|---|---|
| Required items | Methods without a body, associated types without a default (defaults for associated types are unstable), consts without a value. |
| Provided items | Methods with a body and consts with a value. Implementors may override them. |
| Supertraits | trait A: B means every A is also a B, and A's methods may call B's. |
| Generic parameters | trait Convert<T> allows several impls for one type, one per T; an associated type allows only one. |
Usage notes
- Calling. Methods are called with dot syntax if the trait is in scope (
useit if it lives in another module).Trait::method(&x)and<T as Trait>::method(&x)disambiguate between traits with the same method name. - Object safety (dyn compatibility).
dyn Traitworks when methods have a receiver, no generic type parameters, and do not returnSelf. A method can opt out withwhere Self: Sized. - Associated type or generic parameter? Use an associated type when each implementor has one natural choice (
Iterator::Item), and a generic parameter when callers pick (From<T>). - Marker traits (
Send,Sync,Copy,Sized) have no methods.unsafe traitis for traits whose contract the compiler cannot check; implementing one needsunsafe impl. - Associated functions without
selfsuch asfn new() -> Selfare allowed but make the trait non-object-safe unless guarded bywhere Self: Sized. async fnandimpl Traitin trait methods have been supported in traits since Rust 1.75.- Orphan rule. You can implement your trait for any type, and any trait for your type, but not a foreign trait for a foreign type.
Related
impl,dyn,type,where,unsafe- Lessons: Traits, Traits in depth, Associated types