Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 132 ยท Generics

Advanced Traits: Supertraits, Newtype and Disambiguation

Go beyond basic traits in Rust - supertraits, fully qualified syntax, the newtype pattern and orphan rule, marker traits, PhantomData, trait upcasting and impl Trait versus dyn.

You already know how to define a trait, implement it, and use it as a bound. This lesson collects the next layer of trait features that you meet in real code: traits that build on other traits, calls that need to say exactly which trait they mean, a wrapper trick that gets around the "orphan rule", traits with no methods at all, and a zero-sized type called PhantomData that carries information only the compiler sees.

None of these ideas is exotic. Each one solves a specific problem that shows up as soon as a program grows past a few files. We will state the problem first, then the tool. If you need a refresher, read traits, trait bounds and associated types first. The next lesson uses several of these tools to design APIs that cannot be misused.

Supertraits: a trait that requires another trait

Sometimes a trait only makes sense for types that already do something else. A Describe trait that prints a friendly line is only useful if the type can also be shown with {}. Rust lets you write that requirement into the trait itself:

Rust
trait Describe: std::fmt::Display {
    fn describe(&self) -> String {
        format!("<<{self}>>")
    }
}

Display is the supertrait of Describe. Read the colon as "to implement Describe, a type must first implement Display". Inside describe, the compiler lets us use precisely because it knows every implementor is Display. Without the supertrait, the default body would not compile.

Rust A supertrait gives the default method more power

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.

Notice that announce only asks for impl Describe, yet it can still use . A bound on a subtrait automatically brings all its supertraits along.

If you forget the supertrait impl, the compiler tells you precisely what is missing:

Rust Missing the supertrait implementation (fails on purpose)

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.

The compiler reports error[E0277]: `Point` doesn't implement `std::fmt::Display` twice (once at the line impl Describe for Point {}, once at the call to p.describe()), with the note "required by a bound in Describe". The fix is a normal impl fmt::Display for Point.

A trait can have several supertraits, joined with +, as in trait Entity: Clone + fmt::Debug + Send. Think of the list as the checklist a type must complete before it is allowed to join your trait.

Supertraits are not inheritance of data or behavior in the object-oriented sense. Describe: Display does not make Describe a "kind of" Display, it only adds a requirement. A type implements both traits separately, and each trait keeps its own methods.

Same method name, different trait: fully qualified syntax

Rust lets one type implement many traits, and two traits may well have a method with the same name. Normally this is fine. When you call value.name(), the compiler works out which method you mean. If it cannot decide, it asks you to be explicit.

Rust Two traits with the same method name

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.

The lines show the rules:

  • A plain person.fly() picks the inherent method (the one written in impl Human) before any trait method.
  • Pilot::fly(&person) names the trait. Because fly takes &self, the compiler can see from the argument which type to use.
  • <Human as Pilot>::fly(&person) is the full form, called fully qualified syntax: <Type as Trait>::method(args).

The long form becomes necessary when there is no self argument to guide the compiler. This happens with associated functions, such as constructors:

Rust Associated functions need the full form (fails on purpose)

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.

Dog::baby_name() is fine and calls the inherent function. Animal::baby_name() fails with error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type: Rust has no way to guess that you want Dog (the compiler even suggests the fix). Replace the last line with <Dog as Animal>::baby_name() and it prints puppy.

Fully qualified syntax is also how you call a trait method on a generic T without any ambiguity, and how you name a trait's associated types, such as <I as Iterator>::Item. You will rarely need it, but you should recognize it when you see it.

The orphan rule and the newtype pattern

Rust has one rule that surprises people. You may implement a trait for a type only if at least one of them is defined in your own crate. This is the orphan rule. It prevents two libraries from each writing impl Display for Vec<String> and then fighting over which one wins when you use both.

Rust Implementing a foreign trait on a foreign type (fails on purpose)

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.

Display comes from the standard library and so does Vec. The compiler answers error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate and adds that you can define a local type instead.

That is exactly the escape hatch: the newtype pattern. Wrap the foreign type in a tuple struct with one field. The wrapper is your type, so you can implement any trait on it.

Rust The newtype pattern

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.

A newtype costs nothing at run time: the compiler stores NameList exactly like a Vec<String>. The price is only at the source level: the wrapper has none of the inner type's methods, so you reach inside with .0 or you forward the ones you need. If you want every method to work as before, implement Deref:

Rust
use std::ops::Deref;

impl Deref for NameList {
    type Target = Vec<String>;
    fn deref(&self) -> &Vec<String> {
        &self.0
    }
}

With that, names.len() and names.iter() work through automatic dereferencing. Use it sparingly: it exposes the whole inner API, which may not be what you want when the point of the wrapper is to restrict it.

Newtypes have a second, even more common job: giving meaning to a plain value. struct UserId(u64); and struct OrderId(u64); are both just a u64 inside, but the compiler will never let you pass one where the other is expected.

Rust Newtypes keep similar values apart

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.

Uncommenting the last line gives error[E0308]: mismatched types, pointing at the argument with expected `UserId`, found `OrderId` . This is a free bug prevention tool, and in a real program it is far better than a comment saying "this u64 is a user id". See also Display and From for how to add conversions to a newtype.

Marker traits

Some traits have no methods at all. Implementing them is a promise about the type, which the compiler or other code can rely on. The standard library has a handful that appear everywhere.

Trait What it says Who implements it
Copy Duplicating the bits is a complete copy Opt in with derive(Copy)
Sized The size is known at compile time Almost every type, automatically
Send The value can move to another thread Automatically, when all fields are Send
Sync &T can be shared between threads Automatically, when all fields are Sync
Unpin The value is safe to move after being pinned Automatically (see Pin and Unpin)

Send and Sync are auto traits: the compiler adds them for you whenever every field has them, and withholds them otherwise. A type holding an Rc<T> is not Send, because Rc uses non-atomic counters. The lesson on Send and Sync goes deep. Here is a quick way to see the checks:

Rust Asking the compiler which marker traits a type has

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.

You can write your own marker trait too. It is a plain trait with an empty body, used to mark which types may be used in some API:

Rust
trait Sendable {}
impl Sendable for Email {}
impl Sendable for Sms {}

fn deliver<T: Sendable>(message: &T) { /* ... */ }

Sized and ?Sized

Every generic parameter T has an invisible bound T: Sized. That is why you can write fn show<T>(x: T): the compiler needs to know how many bytes of stack to reserve for x. Types like str and [i32] (note: no &) and trait objects such as dyn Display have no size known at compile time. To accept them behind a reference you relax the default with ?Sized:

Rust Relaxing the Sized bound with ?Sized

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.

The ? means "may or may not be". Without ?Sized, show_len("a literal") would be rejected, since T would have to be str. Standard library functions such as AsRef, Borrow and Box<T> use ?Sized for exactly this reason.

PhantomData: a type parameter that holds no data

Sometimes a type should be tagged with another type, though it stores no value of that type. A distance in meters and a distance in feet are both just an f64, yet adding them by mistake famously destroyed a spacecraft. A type parameter that names the unit lets the compiler catch it.

Rust will not allow an unused type parameter, because it would not know how to treat variance and drop. std::marker::PhantomData<T> solves this. It is a zero-sized type (it occupies no memory) that tells the compiler "this struct logically relates to T".

Rust Units of measure with PhantomData

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.

The tag costs nothing: Length<Meters> is 8 bytes, the same as an f64. Mixing units is a compile error because Length<Meters> and Length<Feet> are different types. The next lesson uses PhantomData for the type-state pattern, where the tag says what state an object is in.

Trait upcasting

A trait object &dyn Sub where Sub: Super used to be unusable as a &dyn Super. Since Rust 1.86 it is allowed: this is trait upcasting.

Rust Trait upcasting (Rust 1.86 and newer)

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.

Upcasting works for any supertrait, even a supertrait written as a bound on another trait. It does not go the other way: you cannot turn a &dyn Debug back into &dyn Shape. For that, use Any and downcasting, covered in Advanced trait techniques. See trait objects for the basics of dyn.

impl Trait or dyn Trait?

You now have two ways to say "any type that implements this trait" in a function. They differ in when the real type is decided.

impl Trait (static dispatch) dyn Trait (dynamic dispatch)
Type chosen At compile time, one concrete type per call site At run time
Cost Zero: inlined, no pointer A pointer plus a vtable lookup per call
Code size One copy per type (monomorphization) One copy of the code
Mixed types in one collection No Yes, Vec<Box<dyn Trait>>
Return different types from one function No Yes
Rust impl Trait versus dyn Trait

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.

Choose impl Trait by default: it is faster and gives better error messages. Reach for dyn Trait when you truly need a mixed collection, a plug-in style API, or want to keep compile times and binary size down. A trait is only usable as dyn when it is dyn compatible: no generic methods and no methods returning Self (unless they are opted out with where Self: Sized).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does trait Report: Display mean?

    A supertrait is a requirement. A type must implement Display itself before it can implement Report, and Report's methods may then rely on Display.
  2. 2. When do you need <Dog as Animal>::baby_name() instead of Dog::baby_name()?

    Without a self argument the compiler cannot infer which implementation you mean, and a plain Dog::baby_name() picks the inherent function. Fully qualified syntax names both the type and the trait.
  3. 3. Why can't you write impl Display for Vec<String> in your own crate?

    At least one of the trait or the type must be local. The newtype pattern creates a local wrapper so the rule is satisfied.
  4. 4. What is the size of PhantomData<T>?

    PhantomData is a zero-sized marker. It exists only so the compiler knows the struct is logically tied to T.
  5. 5. Which statement about impl Trait versus dyn Trait is correct?

    dyn Trait uses dynamic dispatch through a vtable, which allows Vec<Box<dyn Trait>> with mixed types. impl Trait is static dispatch and one concrete type per use.

Summary

  • A supertrait (trait A: B) makes B a requirement for implementing A and lets A's methods use B's.
  • When names collide, use Trait::method(&x) or the full form <Type as Trait>::method(...); the full form is required for associated functions without self.
  • The orphan rule stops you from implementing a foreign trait on a foreign type. The newtype pattern wraps the type in a local tuple struct, at no run-time cost, and also separates values like UserId and OrderId.
  • Marker traits (Copy, Sized, Send, Sync, your own) carry promises without methods. ?Sized accepts str, slices and dyn Trait behind a reference.
  • PhantomData tags a type with another type at zero size; it powers unit types and the type-state pattern.
  • Trait upcasting (Rust 1.86) turns &dyn Sub into &dyn Super.
  • Prefer impl Trait for speed; use dyn Trait for mixed collections and run-time choice.

Next: Type-State and Builder Patterns