Skip to content
rusthacks.dev
Generics

Dyn Compatibility in Rust and the Rules That Block dyn

Dyn compatibility is the set of rules a trait must meet to be used as dyn Trait. Learn each rule, the error it produces and how to keep a trait usable.

7 min read
Summarize in AI
Flat illustration for the post “Dyn Compatibility in Rust and the Rules That Block dyn”, composed around errors.

Some traits can be used as dyn Trait and some cannot, and the dividing line is a rule called dyn compatibility. You may know it by its old name, object safety; the compiler renamed it in 2024 and now says "not dyn compatible". The rule exists for a mechanical reason. To call a method through a trait object, the compiler builds a vtable, a table with one function pointer per method, and every entry must be a single concrete function that does not depend on a type the compiler no longer knows. A method that does depend on such a type has no entry to put in the table, so the whole trait is disqualified. This post lists the rules, shows the compiler's message for each one with the real wording from Rust 1.99, and then shows the escape hatches, including a working program that makes a trait with all four problems usable as dyn.

The rules in one table

A trait is dyn compatible when all of these hold:

The trait must not...Because
Have a method with generic type parametersEach instantiation is a separate function, and a vtable needs one fixed entry
Return Self or take Self by value in a method that needs to be callable on dynThe size of Self is unknown behind the pointer
Have an associated function with no self parameter (unless marked where Self: Sized)There is no value to look up the vtable through
Have an associated constantA constant belongs to the type, and there is no type at run time
Require Self: Sized as a supertraitdyn Trait is itself unsized

Each rule is a reason the compiler cannot make one entry in a vtable. A method like fn area(&self) -> f64 has a fixed signature for every implementer, so it fits. A method like fn visit<T: Debug>(&self, item: T) would need one entry per T, an unbounded number, so it does not.

Reading the compiler's reasons

When you write Box<dyn Trait> for a trait that breaks a rule, the error is E0038, and it names the exact method and the exact rule. The message is better than most, so it is worth looking at all four forms.

A generic method:

src/main.rsrust
trait Visitor {
    fn visit<T: Debug>(&self, item: T);
}

fn main() {
    let v: Box<dyn Visitor> = Box::new(Printer);
    v.visit(1);
}
Text
error[E0038]: the trait `Visitor` is not dyn compatible
  --> d1.rs:16:20
   |
16 |     let v: Box<dyn Visitor> = Box::new(Printer);
   |                    ^^^^^^^ `Visitor` is not dyn compatible
   |
note: for a trait to be dyn compatible it needs to allow building a vtable
  --> d1.rs:4:8
   |
 3 | trait Visitor {
   |       ------- this trait is not dyn compatible...
 4 |     fn visit<T: Debug>(&self, item: T);
   |        ^^^^^ ...because method `visit` has generic type parameters
   = help: consider moving `visit` to another trait

A method that returns Self:

Text
note: for a trait to be dyn compatible it needs to allow building a vtable
 1 | trait Duplicate {
   |       --------- this trait is not dyn compatible...
 2 |     fn duplicate(&self) -> Self;
   |                            ^^^^ ...because method `duplicate` references the `Self` type in its return type

An associated function without a receiver:

Text
note: for a trait to be dyn compatible it needs to allow building a vtable
 1 | trait Animal {
   |       ------ this trait is not dyn compatible...
 2 |     fn new(name: &str) -> Self;
   |        ^^^ ...because associated function `new` has no `self` parameter
help: alternatively, consider constraining `new` so it does not apply to trait objects
   |
 2 |     fn new(name: &str) -> Self where Self: Sized;
   |                                +++++++++++++++++

An associated constant:

Text
note: for a trait to be dyn compatible it needs to allow building a vtable
 1 | trait Animal {
   |       ------ this trait is not dyn compatible...
 3 |     const LEGS: u32;
   |           ^^^^ ...because it contains associated const `LEGS`

And a standard library trait, the one people try first:

Text
error[E0038]: the trait `Clone` is not dyn compatible
 --> d5.rs:2:28
  |
2 |     let items: Vec<Box<dyn Clone>> = vec![Box::new(1), Box::new("a")];
  |                            ^^^^^ `Clone` is not dyn compatible
  |
  = note: the trait is not dyn compatible because it requires `Self: Sized`

In each case the message says "this trait is not dyn compatible" and then points at the line that broke the rule and the reason, in words. Read the ...because line first; it is the diagnosis. The help lines vary, from a generic "consider moving to another trait" to a concrete where Self: Sized suggestion.

The escape hatches

You rarely have to give up the method. Four techniques repair each broken rule, and the program below applies all four to one hierarchy and runs.

src/main.rsrust
use std::fmt::Debug;

// 1. Generic method -> take a trait object instead of a type parameter.
trait Visitor {
    fn visit(&self, item: &dyn Debug);
}

struct Printer;

impl Visitor for Printer {
    fn visit(&self, item: &dyn Debug) {
        println!("visited {item:?}");
    }
}

// 2. Returns Self -> return a boxed trait object (the "clone_box" pattern).
trait Shape {
    fn area(&self) -> f64;
    fn clone_box(&self) -> Box<dyn Shape>;
}

#[derive(Clone)]
struct Square(f64);

impl Shape for Square {
    fn area(&self) -> f64 {
        self.0 * self.0
    }
    fn clone_box(&self) -> Box<dyn Shape> {
        Box::new(self.clone())
    }
}

impl Clone for Box<dyn Shape> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

// 3. Constructor with no `self` -> keep it, but opt it out of the vtable.
trait Animal {
    fn new(name: &str) -> Self
    where
        Self: Sized;
    fn speak(&self) -> String;
    // 4. Associated const -> expose it as a method.
    fn legs(&self) -> u32;
}

struct Dog(String);

impl Animal for Dog {
    fn new(name: &str) -> Self {
        Dog(name.to_string())
    }
    fn speak(&self) -> String {
        format!("{} says woof", self.0)
    }
    fn legs(&self) -> u32 {
        4
    }
}

fn main() {
    let v: Box<dyn Visitor> = Box::new(Printer);
    v.visit(&1);
    v.visit(&"text");

    let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0))];
    let copy = shapes.clone();
    println!("cloned {} shape(s), area {}", copy.len(), copy[0].area());

    let a: Box<dyn Animal> = Box::new(Dog::new("rex"));
    println!("{} on {} legs", a.speak(), a.legs());
}
Text
visited 1
visited "text"
cloned 1 shape(s), area 4
rex says woof on 4 legs

Take each repair in turn.

For a generic method, replace the type parameter with a trait object: fn visit(&self, item: &dyn Debug) accepts any Debug value by reference and has one signature, so it fits in a vtable. You lose nothing that matters if the method only needs the trait's behavior, and you pay one more indirect call. The calls v.visit(&1) and v.visit(&"text") print as expected.

For a method returning Self, return a boxed trait object. The pattern in the program is called clone_box: the trait declares fn clone_box(&self) -> Box<dyn Shape>, each implementer returns Box::new(self.clone()), and an impl Clone for Box<dyn Shape> calls it. The vector clone in main then works with shapes.clone(), which is what Vec<Box<dyn Clone>> could not do directly.

For an associated function with no receiver, keep it and add where Self: Sized to that one method. The constraint says "this method exists only for concrete types", so the compiler omits it from the vtable and the rest of the trait remains usable as dyn. You can still call Dog::new("rex") directly, and the object only offers speak and legs.

For an associated constant, expose it as a method: fn legs(&self) -> u32. A method can look the value up through the vtable. If you also want the constant for static use, keep both, with the constant on a second trait or behind where Self: Sized.

Design: split the trait when it has two jobs

The deeper cure is usually to notice that the trait has two roles. One role is "construct me, clone me, give me a constant", which is about the concrete type and is used generically. The other is "behave as a shape", which is used through objects. A trait that mixes them cannot serve both. Split it into a small dyn-compatible trait for the object-facing methods, and keep the construction methods on a second trait or on the concrete type. The standard library does this: Iterator is dyn compatible because the generic adapters (map, filter) carry where Self: Sized, so Box<dyn Iterator<Item = u32>> works and still offers next.

Supertraits add one more consideration. A supertrait that is not dyn compatible makes the subtrait not dyn compatible, which is why a trait with : Clone cannot be an object. Use Debug, Display, Send and Sync as supertraits freely, since they are dyn compatible, and avoid Clone, Sized and Default. Supertraits covers how to compose them.

Which std traits are dyn compatible

Traitdyn works?Note
Debug, Display, ErrorYesBox<dyn Error> is idiomatic
Iterator, Read, WriteYesAdapters need Sized, so use Box<dyn Iterator>
Fn, FnMut, FnOnceYesBox<dyn Fn(u32) -> u32>
AnyYesBasis of downcasting
Clone, Default, SizedNoReturn Self or require Sized
PartialEq, PartialOrd, HashNot directlyTake Self or generics

For the matching error piece with the quickest route from message to fix, see E0038: the trait cannot be made into an object. For the object mechanics themselves, trait objects.

Taggeddyn
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.