Skip to content
Tutorials Center
My learning

Topics

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.

Rust
trait Summary {
    fn author(&self) -> String;
    fn summarize(&self) -> String { format!("(more from {}...)", self.author()) }
}

Try it

Rust Required and provided methods

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.

Rust Associated types, consts and supertraits

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

Rust
[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 (use it 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 Trait works when methods have a receiver, no generic type parameters, and do not return Self. A method can opt out with where 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 trait is for traits whose contract the compiler cannot check; implementing one needs unsafe impl.
  • Associated functions without self such as fn new() -> Self are allowed but make the trait non-object-safe unless guarded by where Self: Sized.
  • async fn and impl Trait in 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.