Rust
E0038 Trait Not Object Safe Fix
E0038 is the trait-object error: the trait works on concrete types, but it cannot be made into an object, because one of its items cannot be entered in the vtable a trait object dispatches through - a method returns Self, a method is generic, the trait carries a constant, the trait demands Sized. This guide separates the eleven shapes that produce it, matches each one to the repair that fits it, and draws the line against the neighboring errors that appear when trait objects are involved.
Written November 25, 2026 · Tested with Rust 1.99.1 · 40 min read
- The rule underneath: one vtable, fixed in advance
- How to read the diagnostic
- The first failure: a method that returns Self
- The second failure: a generic method
Written November 25, 2026
Tested with Rust 1.99.1
What this guide is
Error E0038 is the dyn-compatibility error - object safety, in the older term. The error codes index puts it this way: some traits are not allowed to be used as trait object types, and attempting to use one as dyn Trait triggers E0038. The trait itself is not broken. Every failure in this guide compiles and runs on concrete types; the error appears only at the point where the program names the trait object type - a Box<dyn Trait>, a &dyn Trait - because that is the point where the compiler has to build the vtable, the table of method pointers a trait object dispatches through, and one item in the trait cannot be entered in it.
The Reference states the conditions as a list: all supertraits must themselves be dyn compatible, Sized must not be a supertrait, the trait must not have any associated constants or associated types with generics, and every associated function must be dispatchable from a trait object - no type parameters, Self used only in the receiver, no opaque return type - or explicitly non-dispatchable through a where Self: Sized bound. Each family in this guide is one clause of that list, isolated in a small program: a method returning Self, a generic method, a Self argument, a missing receiver, an associated constant, a Sized requirement, Self inside a supertrait listing, an impl Trait return, a Box<Self> return, and the standard Clone trait, which fails the test as a whole.
The repairs fall into a few groups. Exclude the offending method from the vtable with where Self: Sized, and it stays callable on concrete types while the rest of the trait becomes an object. Reshape the method so it names a trait object instead of Self - return Box<dyn Trait>, take &dyn Trait. Remove the item that cannot be in a vtable at all - replace an associated constant with a method, drop a Sized supertrait. Or give up the trait object for that use and take static dispatch, a generic function, which places no conditions on the trait at all. Which repair fits depends on which clause failed, and the diagnostic names the clause, so reading it comes first.
Build every program in this guide with rustc --edition 2021. In the compiler transcripts below, the file names are the bare names shown on the command line.
The rule underneath: one vtable, fixed in advance
A trait object pairs a pointer to the value with a pointer to a vtable - one table per trait implementation, holding a function pointer for each method, as the error codes index describes. A call through Box<dyn Trait> reads the pointer out of the table and calls it. That single fact generates every condition in this guide. The table is built at compile time, before the program knows which concrete types will sit behind the pointer, so every entry in it must be a single function with a single, fully known signature.
A generic method would need one entry per type it is ever called with, and that set is open - the index works the arithmetic for a method called with three types across ten implementers and gets thirty implementations where the table has room for one slot. A method returning Self has a return type the table cannot state, because Self is a different type for each implementer and the caller through the object cannot name it. A method with no receiver cannot be reached through the table at all, since there is no object to read the table pointer from. An associated constant is not a function, so it has no entry to make. A trait that requires Self: Sized excludes the trait object itself, because dyn Trait is unsized - and since dyn Trait always implements Trait, a sized trait can never have a trait object, as the index's Sized section explains.
The one deliberate escape is the where Self: Sized bound on a single method. It marks the method explicitly non-dispatchable in the Reference's terms: the method is left out of the vtable, remains callable on every concrete implementer, and no longer blocks the rest of the trait from becoming an object. Several repairs below are exactly this, and the neighbors show the same traits with the bound already in place. The bound is per method, not per trait - putting Sized on the trait itself is the seventh failure, not a repair.
How to read the diagnostic
Ten of the eleven families print the same header - error E0038, "the trait is not dyn compatible" - with the span on the dyn type in main, and then a note that points back into the trait definition and finishes the sentence "...because" with the specific clause that failed. The eleventh, the standard Clone trait, prints the header and the span but states its clause in a plain note line of its own - "the trait is not dyn compatible because it requires Self: Sized" - with no span into a trait definition, because that trait is the standard library's, not the program's. The first family's, in full:
$ rustc --edition 2021 fail_return_self.rs -o fail_return_self
error[E0038]: the trait `Maker` is not dyn compatible
--> fail_return_self.rs:4:28
|
4 | fn main() { let b: Box<dyn Maker> = Box::new(A); let m = b.make(); println!("{}", m.v()); }
| ^^^^^ `Maker` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_return_self.rs:1:33
|
1 | trait Maker { fn make(&self) -> Self; fn v(&self) -> i32; }
| ----- ^^^^ ...because method `make` references the `Self` type in its return type
| |
| this trait is not dyn compatible...
= help: consider moving `make` to another trait
= help: only type `A` implements `Maker`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
Read it in order. The header names the trait, not the problem. The note is where the information is: it underlines the offending item in the trait - here Self in the return position of make - and states the reason in its last line, "because method make references the Self type in its return type". Each of those ten families has the same shape with a different last line: "has generic type parameters", "contains associated const", "requires Self: Sized", "uses Self as a type parameter", "references an impl Trait type in its return type". That line is the diagnosis; the repair is chosen from it, not from the header. Two helps may follow - "consider moving the method to another trait", which is the trait-splitting repair, and a note that only one type implements the trait in the program at hand, which is a property of these small examples, not of the error. The reading above is scoped to the forms printed in this guide.
The first failure: a method that returns Self
A maker trait whose method produces a new value of the implementing type:
trait Maker { fn make(&self) -> Self; fn v(&self) -> i32; }
struct A;
impl Maker for A { fn make(&self) -> Self { A } fn v(&self) -> i32 { 1 } }
fn main() { let b: Box<dyn Maker> = Box::new(A); let m = b.make(); println!("{}", m.v()); }
$ rustc --edition 2021 fail_return_self.rs -o fail_return_self
error[E0038]: the trait `Maker` is not dyn compatible
--> fail_return_self.rs:4:28
|
4 | fn main() { let b: Box<dyn Maker> = Box::new(A); let m = b.make(); println!("{}", m.v()); }
| ^^^^^ `Maker` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_return_self.rs:1:33
|
1 | trait Maker { fn make(&self) -> Self; fn v(&self) -> i32; }
| ----- ^^^^ ...because method `make` references the `Self` type in its return type
| |
| this trait is not dyn compatible...
= help: consider moving `make` to another trait
= help: only type `A` implements `Maker`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait Maker { fn make(&self) -> Box<dyn Maker>; fn v(&self) -> i32; }
struct A;
impl Maker for A { fn make(&self) -> Box<dyn Maker> { Box::new(A) } fn v(&self) -> i32 { 1 } }
fn main() { let b: Box<dyn Maker> = Box::new(A); let m = b.make(); println!("{}", m.v()); }
$ rustc --edition 2021 fix_return_self.rs -o fix_return_self
$ ./fix_return_self
1
Through a trait object, the caller cannot name the type make returns - Self is whichever concrete type sits behind the pointer, and the vtable entry would need a different return type per implementer. The note underlines Self in the return position and says so. The fix returns a trait object instead: Box<dyn Maker> is one type regardless of the implementer, so the entry fits the table, and the returned object still answers the trait's other method.
The output is 1, the made object's v. The same trait repaired by exclusion instead - make given a where Self: Sized bound and called only on concrete types - is in the neighbors below, and the static-dispatch repair for this exact trait is in the alternatives.
The second failure: a generic method
A sink trait with one ordinary method and one method generic over the value it takes:
trait Sink { fn get(&self) -> i32; fn put<T>(&self, v: T); }
struct A;
impl Sink for A { fn get(&self) -> i32 { 5 } fn put<T>(&self, _v: T) {} }
fn main() { let b: Box<dyn Sink> = Box::new(A); b.put(1); println!("{}", b.get()); }
$ rustc --edition 2021 fail_generic_method.rs -o fail_generic_method
error[E0038]: the trait `Sink` is not dyn compatible
--> fail_generic_method.rs:4:28
|
4 | fn main() { let b: Box<dyn Sink> = Box::new(A); b.put(1); println!("{}", b.get()); }
| ^^^^ `Sink` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_generic_method.rs:1:39
|
1 | trait Sink { fn get(&self) -> i32; fn put<T>(&self, v: T); }
| ---- ^^^ ...because method `put` has generic type parameters
| |
| this trait is not dyn compatible...
= help: consider moving `put` to another trait
= help: only type `A` implements `Sink`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait Sink { fn get(&self) -> i32; fn put<T>(&self, v: T) where Self: Sized; }
struct A;
impl Sink for A { fn get(&self) -> i32 { 5 } fn put<T>(&self, _v: T) where Self: Sized {} }
fn main() { A.put(1); let b: Box<dyn Sink> = Box::new(A); println!("{}", b.get()); }
$ rustc --edition 2021 fix_generic_method.rs -o fix_generic_method
$ ./fix_generic_method
5
A vtable holds one pointer per method, and a generic method is a family of functions - one per type parameter it is called with, generated by monomorphization. There is no single pointer to enter, and the set of types is open, so the note reads "because method put has generic type parameters". The fix excludes put from the vtable with where Self: Sized: the trait becomes an object through get, and put remains available on the concrete type, which is where the fixed program calls it - on A itself, before the box is made.
The output is 5. The error codes index offers the same bound for this shape, and a second route when exclusion is not an option: replace the type parameter with another trait object, such as taking Box<dyn OtherTrait> in place of a generic T.
The third failure: a method that takes Self by value
A combine method that consumes a second value of the same type:
trait Comb { fn v(&self) -> i32; fn combine(&self, other: Self) -> i32; }
struct A;
impl Comb for A { fn v(&self) -> i32 { 1 } fn combine(&self, other: Self) -> i32 { self.v() + other.v() } }
fn main() { let b: Box<dyn Comb> = Box::new(A); println!("{}", b.combine(A)); }
$ rustc --edition 2021 fail_self_arg.rs -o fail_self_arg
error[E0038]: the trait `Comb` is not dyn compatible
--> fail_self_arg.rs:4:28
|
4 | fn main() { let b: Box<dyn Comb> = Box::new(A); println!("{}", b.combine(A)); }
| ^^^^ `Comb` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_self_arg.rs:1:59
|
1 | trait Comb { fn v(&self) -> i32; fn combine(&self, other: Self) -> i32; }
| ---- this trait is not dyn compatible... ^^^^ ...because method `combine` references the `Self` type in this parameter
= help: consider moving `combine` to another trait
= help: only type `A` implements `Comb`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait Comb { fn v(&self) -> i32; fn combine(&self, other: &dyn Comb) -> i32; }
struct A;
impl Comb for A { fn v(&self) -> i32 { 1 } fn combine(&self, other: &dyn Comb) -> i32 { self.v() + other.v() } }
fn main() { let b: Box<dyn Comb> = Box::new(A); println!("{}", b.combine(&A)); }
$ rustc --edition 2021 fix_self_arg.rs -o fix_self_arg
$ ./fix_self_arg
2
The receiver is the one place Self may appear, per the Reference: a dispatchable method must not use Self except in the type of the receiver. An argument of type Self breaks that twice over - its size is unknown through the object, and nothing guarantees the argument behind the call is the same concrete type as the receiver. The fix passes the other value as a trait object, &dyn Comb, and combines through the trait's own method, which is all the implementation ever used.
The output is 2 - the two values' v results added. Where the argument's concrete type genuinely matters, the alternatives are the where Self: Sized exclusion or a generic function; where only trait behavior is used, the trait-object argument is the repair that keeps dynamic dispatch.
The fourth failure: a method that takes a reference to Self
The comparison shape - a method that takes &Self, the form equality-style traits take:
trait Cmp2 { fn key(&self) -> i32; fn same(&self, other: &Self) -> bool; }
struct A;
impl Cmp2 for A { fn key(&self) -> i32 { 3 } fn same(&self, other: &Self) -> bool { self.key() == other.key() } }
fn main() { let b: Box<dyn Cmp2> = Box::new(A); println!("{}", b.same(&A)); }
$ rustc --edition 2021 fail_ref_self_arg.rs -o fail_ref_self_arg
error[E0038]: the trait `Cmp2` is not dyn compatible
--> fail_ref_self_arg.rs:4:28
|
4 | fn main() { let b: Box<dyn Cmp2> = Box::new(A); println!("{}", b.same(&A)); }
| ^^^^ `Cmp2` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_ref_self_arg.rs:1:58
|
1 | trait Cmp2 { fn key(&self) -> i32; fn same(&self, other: &Self) -> bool; }
| ---- this trait is not dyn compatible... ^^^^^ ...because method `same` references the `Self` type in this parameter
= help: consider moving `same` to another trait
= help: only type `A` implements `Cmp2`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait Cmp2 { fn key(&self) -> i32; fn same(&self, other: &dyn Cmp2) -> bool; }
struct A;
impl Cmp2 for A { fn key(&self) -> i32 { 3 } fn same(&self, other: &dyn Cmp2) -> bool { self.key() == other.key() } }
fn main() { let b: Box<dyn Cmp2> = Box::new(A); println!("{}", b.same(&A)); }
$ rustc --edition 2021 fix_ref_self_arg.rs -o fix_ref_self_arg
$ ./fix_ref_self_arg
true
A reference does not rescue the argument. &Self is still Self in a parameter position, and through a trait object the compiler cannot promise that the referenced value has the receiver's concrete type - a &dyn Cmp2 call could pair any two implementers. The fix compares through the trait instead: same takes &dyn Cmp2 and compares the key values both objects report, which is the part of the comparison that was ever about the concrete type.
The output is true. This is the shape readers meet in traits modeled on equality or ordering, where the other operand starts life as Self or &Self: the trait-object form of such a method has to be restated in terms of what the trait can ask both sides, or excluded with where Self: Sized and kept for concrete types.
The fifth failure: a method with no receiver
A factory-style associated function alongside an ordinary method:
trait Fact { fn create() -> u8; fn v(&self) -> u8; }
struct A;
impl Fact for A { fn create() -> u8 { 7 } fn v(&self) -> u8 { 7 } }
fn main() { let b: Box<dyn Fact> = Box::new(A); println!("{}", b.v()); }
$ rustc --edition 2021 fail_no_receiver.rs -o fail_no_receiver
error[E0038]: the trait `Fact` is not dyn compatible
--> fail_no_receiver.rs:4:28
|
4 | fn main() { let b: Box<dyn Fact> = Box::new(A); println!("{}", b.v()); }
| ^^^^ `Fact` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_no_receiver.rs:1:17
|
1 | trait Fact { fn create() -> u8; fn v(&self) -> u8; }
| ---- ^^^^^^ ...because associated function `create` has no `self` parameter
| |
| this trait is not dyn compatible...
= help: only type `A` implements `Fact`; consider using it directly instead.
help: consider turning `create` into a method by giving it a `&self` argument
|
1 | trait Fact { fn create(&self) -> u8; fn v(&self) -> u8; }
| +++++
help: alternatively, consider constraining `create` so it does not apply to trait objects
|
1 | trait Fact { fn create() -> u8 where Self: Sized; fn v(&self) -> u8; }
| +++++++++++++++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait Fact { fn create() -> u8 where Self: Sized; fn v(&self) -> u8; }
struct A;
impl Fact for A { fn create() -> u8 { 7 } fn v(&self) -> u8 { 7 } }
fn main() { println!("{}", A::create()); let b: Box<dyn Fact> = Box::new(A); println!("{}", b.v()); }
$ rustc --edition 2021 fix_no_receiver.rs -o fix_no_receiver
$ ./fix_no_receiver
7
7
A method with no self parameter cannot be called through a trait object, as the error codes index puts it, because there is no way to get a pointer to the method table for it - the table is reached through an object, and this call has none. Calling it as <A as Fact>::create() would have to pick an implementation with no value to pick it from. The fix is the exclusion the index suggests: create takes a where Self: Sized bound, leaves the vtable, and is called on the concrete type, while v carries the trait object.
The output is 7 twice - the associated function on A, then the method through the box. An associated function that every implementer must provide is not in itself a problem; it only has to be marked as not part of the object.
The sixth failure: an associated constant
A trait that carries a constant alongside its method:
trait Named { const NAME: &'static str; fn v(&self) -> i32; }
struct A;
impl Named for A { const NAME: &'static str = "a"; fn v(&self) -> i32 { 1 } }
fn main() { let b: Box<dyn Named> = Box::new(A); println!("{}", b.v()); }
$ rustc --edition 2021 fail_assoc_const.rs -o fail_assoc_const
error[E0038]: the trait `Named` is not dyn compatible
--> fail_assoc_const.rs:4:28
|
4 | fn main() { let b: Box<dyn Named> = Box::new(A); println!("{}", b.v()); }
| ^^^^^ `Named` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_assoc_const.rs:1:21
|
1 | trait Named { const NAME: &'static str; fn v(&self) -> i32; }
| ----- ^^^^ ...because it contains associated const `NAME`
| |
| this trait is not dyn compatible...
= help: consider moving `NAME` to another trait
= help: only type `A` implements `Named`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait Named { fn name(&self) -> &'static str; fn v(&self) -> i32; }
struct A;
impl Named for A { fn name(&self) -> &'static str { "a" } fn v(&self) -> i32 { 1 } }
fn main() { let b: Box<dyn Named> = Box::new(A); println!("{} {}", b.name(), b.v()); }
$ rustc --edition 2021 fix_assoc_const.rs -o fix_assoc_const
$ ./fix_assoc_const
a 1
Associated constants are not stored on the method table - the error codes index makes the point by pairing them with static functions - so a trait containing one cannot be dyn compatible, and the Reference lists "it must not have any associated constants" as a condition of its own. The note names the constant: "because it contains associated const NAME". The repair is the workaround the index gives: a helper method instead of the constant. A method has a vtable entry, returns the same value, and the trait becomes an object.
The output is a 1 - the name the constant carried, now returned by name, and the method's 1. Where different implementers genuinely report different values, the method form is also the more honest shape: the value was always per-implementer, and the method says so.
The seventh failure: a trait that requires Self: Sized
A trait with an ordinary method, declared with Sized as a supertrait:
trait SizedT: Sized { fn v(&self) -> i32; }
struct A;
impl SizedT for A { fn v(&self) -> i32 { 1 } }
fn main() { let b: Box<dyn SizedT> = Box::new(A); println!("{}", b.v()); }
$ rustc --edition 2021 fail_sized.rs -o fail_sized
error[E0038]: the trait `SizedT` is not dyn compatible
--> fail_sized.rs:4:28
|
4 | fn main() { let b: Box<dyn SizedT> = Box::new(A); println!("{}", b.v()); }
| ^^^^^^ `SizedT` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_sized.rs:1:15
|
1 | trait SizedT: Sized { fn v(&self) -> i32; }
| ------ ^^^^^ ...because it requires `Self: Sized`
| |
| this trait is not dyn compatible...
= help: only type `A` implements `SizedT`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait SizedT { fn v(&self) -> i32; }
struct A;
impl SizedT for A { fn v(&self) -> i32 { 1 } }
fn main() { let b: Box<dyn SizedT> = Box::new(A); println!("{}", b.v()); }
$ rustc --edition 2021 fix_sized.rs -o fix_sized
$ ./fix_sized
1
Nothing in the method is wrong; the trait's own bound is the failure, and the note says so - "because it requires Self: Sized". A trait object is unsized by construction, and dyn Trait always implements Trait, so a trait that demands Sized of its implementers can never be implemented by its own trait object. The error codes index notes that Self: Sized is generally used to indicate a trait should not be used as a trait object, and that if the trait is your own, the repair is to remove the restriction. That is the whole fix here: the bound comes off, the method is unchanged.
The output is 1. Contrast the per-method bound in the earlier families: where Self: Sized on one method excludes that method; Sized on the trait excludes the object entirely.
The eighth failure: Self in a supertrait listing
A subtrait that names its supertrait with Self as the type parameter - the example from the error codes index, made concrete with a method on the supertrait:
trait Super<A: ?Sized> { fn get_a(&self) -> &A; }
trait Sub: Super<Self> {}
struct Foo;
impl Super<Foo> for Foo { fn get_a(&self) -> &Foo { self } }
impl Sub for Foo {}
fn main() { let _x: Box<dyn Sub> = Box::new(Foo); }
$ rustc --edition 2021 fail_super_self.rs -o fail_super_self
error[E0038]: the trait `Sub` is not dyn compatible
--> fail_super_self.rs:6:29
|
6 | fn main() { let _x: Box<dyn Sub> = Box::new(Foo); }
| ^^^ `Sub` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_super_self.rs:2:12
|
2 | trait Sub: Super<Self> {}
| --- ^^^^^^^^^^^ ...because it uses `Self` as a type parameter
| |
| this trait is not dyn compatible...
= help: only type `Foo` implements `Sub`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait Super<A: ?Sized> { fn get_a(&self) -> &A; }
trait Sub: Super<String> {}
struct Foo(String);
impl Super<String> for Foo { fn get_a(&self) -> &String { &self.0 } }
impl Sub for Foo {}
fn main() { let b: Box<dyn Sub> = Box::new(Foo("hi".to_string())); println!("{}", b.get_a()); }
$ rustc --edition 2021 fix_super_self.rs -o fix_super_self
$ ./fix_super_self
hi
The supertrait itself is dyn compatible - get_a returns a reference to its parameter, which is fine when the parameter is a known type. Naming the parameter Self makes the return type of a supertrait method depend on the implementer, so through the object it is unknown, and the note reads "because it uses Self as a type parameter". The index is blunt about this shape: there is no easy fix, and code generally needs refactoring so the supertrait no longer derives from Super<Self>. The fixed program is that refactoring in its smallest form - the parameter is a concrete type, String, the struct holds one, and get_a returns a reference to it, exactly the Super<String> arrangement the index names as acceptable.
The output is hi, the string the Foo value holds, read back through the trait object.
The ninth failure: a method that returns impl Trait
A generator trait whose method returns an iterator as an opaque type:
trait Gen { fn vals(&self) -> impl Iterator<Item = i32>; }
struct A;
impl Gen for A { fn vals(&self) -> impl Iterator<Item = i32> { [1, 2].into_iter() } }
fn main() { let b: Box<dyn Gen> = Box::new(A); println!("{}", b.vals().count()); }
$ rustc --edition 2021 fail_impl_trait.rs -o fail_impl_trait
error[E0038]: the trait `Gen` is not dyn compatible
--> fail_impl_trait.rs:4:28
|
4 | fn main() { let b: Box<dyn Gen> = Box::new(A); println!("{}", b.vals().count()); }
| ^^^ `Gen` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_impl_trait.rs:1:31
|
1 | trait Gen { fn vals(&self) -> impl Iterator<Item = i32>; }
| --- ^^^^^^^^^^^^^^^^^^^^^^^^^ ...because method `vals` references an `impl Trait` type in its return type
| |
| this trait is not dyn compatible...
= help: consider moving `vals` to another trait
= help: only type `A` implements `Gen`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait Gen { fn vals(&self) -> Box<dyn Iterator<Item = i32>>; }
struct A;
impl Gen for A { fn vals(&self) -> Box<dyn Iterator<Item = i32>> { Box::new([1, 2].into_iter()) } }
fn main() { let b: Box<dyn Gen> = Box::new(A); println!("{}", b.vals().count()); }
$ rustc --edition 2021 fix_impl_trait.rs -o fix_impl_trait
$ ./fix_impl_trait
2
An impl Trait return is a concrete type the compiler picks per implementation and hides from the caller - which is precisely what a vtable entry cannot be. The Reference lists the opaque return type among the things a dispatchable function must not have, and the note states it directly: the method "references an impl Trait type in its return type". The fix names the erasure explicitly instead of hiding it: the method returns Box<dyn Iterator<Item = i32>>, one type for every implementer, with the item type stated.
The output is 2, the count of the two elements. The pattern generalizes to any impl Trait return in a trait meant for objects: box the trait object the opaque type was standing in for, and state its parameters.
The tenth failure: a method that returns Box of Self
A cloning-shaped method that returns the value boxed - the shape that looks already object-ready, because a box is a pointer:
trait Boxer { fn boxed(&self) -> Box<Self>; fn v(&self) -> i32; }
struct A;
impl Boxer for A { fn boxed(&self) -> Box<Self> { Box::new(A) } fn v(&self) -> i32 { 6 } }
fn main() { let b: Box<dyn Boxer> = Box::new(A); println!("{}", b.boxed().v()); }
$ rustc --edition 2021 fail_box_self.rs -o fail_box_self
error[E0038]: the trait `Boxer` is not dyn compatible
--> fail_box_self.rs:4:28
|
4 | fn main() { let b: Box<dyn Boxer> = Box::new(A); println!("{}", b.boxed().v()); }
| ^^^^^ `Boxer` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> fail_box_self.rs:1:34
|
1 | trait Boxer { fn boxed(&self) -> Box<Self>; fn v(&self) -> i32; }
| ----- ^^^^^^^^^ ...because method `boxed` references the `Self` type in its return type
| |
| this trait is not dyn compatible...
= help: consider moving `boxed` to another trait
= help: only type `A` implements `Boxer`; consider using it directly instead.
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
trait Boxer { fn boxed(&self) -> Box<dyn Boxer>; fn v(&self) -> i32; }
struct A;
impl Boxer for A { fn boxed(&self) -> Box<dyn Boxer> { Box::new(A) } fn v(&self) -> i32 { 6 } }
fn main() { let b: Box<dyn Boxer> = Box::new(A); println!("{}", b.boxed().v()); }
$ rustc --edition 2021 fix_box_self.rs -o fix_box_self
$ ./fix_box_self
6
The box does not change what is inside it. Box<Self> still names a different concrete type per implementer, and a caller through the trait object would receive a box whose contents it cannot name - Self in the return type is the failure wherever it sits, nested or not, just as the nested Vec<Self> and Option<Self> forms fail with E0038 alongside their own Sized errors. The fix boxes the trait object instead of the concrete type: Box<dyn Boxer> is the same type from every implementer, and the returned object answers the trait's methods.
The output is 6. This is the standard shape behind clone-through-an-object designs: a method that returns Box<dyn Trait> can duplicate a value whose concrete type the caller never learns.
The eleventh failure: Box of dyn Clone
The standard library's own non-object-safe trait, used the way readers first try to use it:
fn main() { let b: Box<dyn Clone> = Box::new(1i32); let _ = b.clone(); }
$ rustc --edition 2021 fail_dyn_clone.rs -o fail_dyn_clone
error[E0038]: the trait `Clone` is not dyn compatible
--> fail_dyn_clone.rs:1:28
|
1 | fn main() { let b: Box<dyn Clone> = Box::new(1i32); let _ = b.clone(); }
| ^^^^^ `Clone` is not dyn compatible
|
= note: the trait is not dyn compatible because it requires `Self: Sized`
= note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0038`.
fn dup<T: Clone>(t: &T) -> T { t.clone() }
fn main() { let x = 41i32; let y = dup(&x); println!("{}", y + 1); }
$ rustc --edition 2021 fix_dyn_clone.rs -o fix_dyn_clone
$ ./fix_dyn_clone
42
Clone is declared pub trait Clone: Sized with fn clone(&self) -> Self - it carries both the Sized requirement and a Self return, and the diagnostic for this program names the first of them: "the trait is not dyn compatible because it requires Self: Sized". There is no edit to Clone available, so the repair is to change the dispatch, not the trait. Where the set of types is known at the call site, static dispatch does everything Clone does: the generic dup clones any Clone type, monomorphized per call.
The output is 42 - the clone of 41, plus one. Where a program genuinely needs to clone values held as trait objects, the tenth family's shape is the route: a trait of your own whose method returns Box<dyn ThatTrait>, implemented per type.
Seven more shapes that fail the same way
The same header - "the trait is not dyn compatible" with code E0038, exactly one error and no other code - for seven more programs. Each is repaired by the same moves as the families above: exclude the method with where Self: Sized, restate it in trait objects, or take static dispatch:
A generic method whose type parameter appears only in its return, bounded by a conversion trait:
trait Conv { fn conv<T: From<i32>>(&self) -> T; }
struct A;
impl Conv for A { fn conv<T: From<i32>>(&self) -> T { T::from(1) } }
fn main() { let b: Box<dyn Conv> = Box::new(A); let _x: i32 = b.conv(); }
An associated constant carried by a supertrait rather than the trait itself:
trait HasC { const C: i32; }
trait Child: HasC { fn v(&self) -> i32; }
struct A;
impl HasC for A { const C: i32 = 1; }
impl Child for A { fn v(&self) -> i32 { 1 } }
fn main() { let b: Box<dyn Child> = Box::new(A); println!("{}", b.v()); }
A store method that takes Self as its argument:
trait Store { fn store(&self, v: Self); }
struct A;
impl Store for A { fn store(&self, _v: Self) {} }
fn main() { let b: Box<dyn Store> = Box::new(A); b.store(A); }
A method that takes Box<Self> as an argument:
trait Take { fn take(&self, b: Box<Self>) -> i32; }
struct A;
impl Take for A { fn take(&self, _b: Box<Self>) -> i32 { 1 } }
fn main() { let b: Box<dyn Take> = Box::new(A); println!("{}", b.take(Box::new(A))); }
A subtrait whose supertrait returns Self, so the incompatibility is inherited:
trait Maker { fn make(&self) -> Self; }
trait Child: Maker { fn v(&self) -> i32; }
struct A;
impl Maker for A { fn make(&self) -> Self { A } }
impl Child for A { fn v(&self) -> i32 { 1 } }
fn main() { let b: Box<dyn Child> = Box::new(A); println!("{}", b.v()); }
A method generic over a const parameter:
trait CG { fn f<const N: usize>(&self) -> usize; }
struct A;
impl CG for A { fn f<const N: usize>(&self) -> usize { N } }
fn main() { let b: Box<dyn CG> = Box::new(A); println!("{}", b.f::<3>()); }
A method that returns a reference to Self:
trait RefT { fn other(&self) -> &Self; }
struct A;
impl RefT for A { fn other(&self) -> &Self { self } }
fn main() { let b: Box<dyn RefT> = Box::new(A); let _ = b.other(); }
When the trait itself cannot change
Static dispatch is the genuinely different repair, and it is the eleventh family's fix generalized. A generic function places no dyn-compatibility conditions on a trait at all - no vtable is built, each call is monomorphized for the concrete type it receives - so a trait that returns Self, like the first family's Maker, works unchanged when the object is never needed:
trait Maker { fn make(&self) -> Self; fn v(&self) -> i32; }
struct A;
impl Maker for A { fn make(&self) -> Self { A } fn v(&self) -> i32 { 1 } }
fn make_value<T: Maker>(m: &T) -> i32 { m.make().v() }
fn main() { println!("{}", make_value(&A)); }
$ rustc --edition 2021 alt_static_dispatch.rs -o alt_static_dispatch
$ ./alt_static_dispatch
1
The output is 1. The trade is the usual one between the two dispatch forms: the generic function must know the concrete type at each call, so it cannot hold values of several types in one collection the way Vec<Box<dyn Maker>> would. Choose it when the call sites each have one type; choose the trait-object repairs when the program's point is that the type varies at run time.
The neighbors that compile
These programs sit one item away from the failures and compile as written, each because the one offending item is excluded, named, or never made into an object.
A plain trait as an object - one &self method, nothing else in the trait:
trait Draw { fn draw(&self) -> i32; }
struct A;
impl Draw for A { fn draw(&self) -> i32 { 4 } }
fn main() { let b: Box<dyn Draw> = Box::new(A); println!("{}", b.draw()); }
$ rustc --edition 2021 ok_plain.rs -o ok_plain
$ ./ok_plain
4
The output is 4. This is the baseline every family above deviates from by one item.
A generic method excluded with Self: Sized - the second family's repair, with the method called on the concrete type and the rest of the trait used as an object:
trait Mix { fn get(&self) -> i32; fn put<T>(&self, v: T) where Self: Sized; }
struct A;
impl Mix for A { fn get(&self) -> i32 { 5 } fn put<T>(&self, _v: T) where Self: Sized {} }
fn main() { A.put(1); let b: Box<dyn Mix> = Box::new(A); println!("{}", b.get()); }
$ rustc --edition 2021 ok_generic_excluded.rs -o ok_generic_excluded
$ ./ok_generic_excluded
5
The output is 5.
A trait object with its associated type named - an associated type does not block an object; it has to be fixed in the object type, the way Iterator is used as dyn Iterator<Item = u8>:
trait Prod2 { type Out; fn get(&self) -> Self::Out; }
struct A;
impl Prod2 for A { type Out = i32; fn get(&self) -> i32 { 3 } }
fn main() { let b: Box<dyn Prod2<Out = i32>> = Box::new(A); println!("{}", b.get()); }
$ rustc --edition 2021 ok_assoc_named.rs -o ok_assoc_named
$ ./ok_assoc_named
3
The output is 3. Leaving the type unnamed is the first trap below, and it is a different error.
A Self-returning method excluded with Self: Sized - the first family's other repair:
trait Mk { fn v(&self) -> i32; fn make(&self) -> Self where Self: Sized; }
struct A;
impl Mk for A { fn v(&self) -> i32 { 2 } fn make(&self) -> Self { A } }
fn main() { let a = A.make(); println!("{}", a.v()); let b: Box<dyn Mk> = Box::new(A); println!("{}", b.v()); }
$ rustc --edition 2021 ok_return_self_excluded.rs -o ok_return_self_excluded
$ ./ok_return_self_excluded
2
2
The output is 2 twice - through the concrete value the excluded method produced, then through the object.
An associated function excluded with Self: Sized - the fifth family's repair:
trait Fac2 { fn create() -> u8 where Self: Sized; fn v(&self) -> u8; }
struct A;
impl Fac2 for A { fn create() -> u8 { 7 } fn v(&self) -> u8 { 7 } }
fn main() { println!("{}", A::create()); let b: Box<dyn Fac2> = Box::new(A); println!("{}", b.v()); }
$ rustc --edition 2021 ok_assoc_fn_excluded.rs -o ok_assoc_fn_excluded
$ ./ok_assoc_fn_excluded
7
7
The output is 7 twice - the associated function on the concrete type, then the method through the object.
A non-object-safe trait used on a concrete type - no dyn anywhere, so no vtable is ever requested and the Self return is unproblematic:
trait Maker2 { fn make(&self) -> Self; }
struct A;
impl Maker2 for A { fn make(&self) -> Self { A } }
fn main() { let a = A.make(); let _ = a; println!("ok"); }
$ rustc --edition 2021 ok_concrete.rs -o ok_concrete
$ ./ok_concrete
ok
The output is ok. E0038 is an error about the object type, not about the trait.
The fixes in reach order
- The method is the only problem and concrete callers still need it: exclude it - add
where Self: Sizedto that method. The second, fifth, and (in the neighbors) first families are this repair. - The method can be restated without
Self: return or take a trait object -Box<dyn Trait>in place ofSelforBox<Self>,&dyn Traitin place ofSelfor&Self. The first, third, fourth, ninth, and tenth families. - The blocker is an item, not a method: replace the associated constant with a method, or drop the trait's
Sizedrequirement. The sixth and seventh families. Selfsits inside a supertrait listing: refactor the parameter to a concrete type. The eighth family - the one shape with no local edit.- The trait is not yours, or the object is not needed: static dispatch - a generic function or a generic type parameter. The eleventh family and the alternatives.
- The header is not E0038: an unnamed associated type is E0191, a by-value receiver called on an object is E0161, a non-implementer is E0277, a missing method is E0599, a move out of a trait object is E0308, and a call to an excluded method on an object carries no code at all - all in the traps.
Traps
- A trait object whose associated type is not named is E0191, not E0038. An associated type does not make a trait incompatible - the neighbors name one on the object type and compile - but leaving it out is its own error, whose index page states the rule: trait objects need to have all associated types specified:
trait Prod { type Out; fn get(&self) -> Self::Out; }
struct A;
impl Prod for A { type Out = i32; fn get(&self) -> i32 { 3 } }
fn main() { let b: Box<dyn Prod> = Box::new(A); println!("{}", b.get()); }
$ rustc --edition 2021 trap_assoc_unnamed.rs -o trap_assoc_unnamed
error[E0191]: the value of the associated type `Out` in `Prod` must be specified
--> trap_assoc_unnamed.rs:4:28
|
1 | trait Prod { type Out; fn get(&self) -> Self::Out; }
| -------- `Out` defined here
...
4 | fn main() { let b: Box<dyn Prod> = Box::new(A); println!("{}", b.get()); }
| ^^^^
|
help: specify the associated type
|
4 | fn main() { let b: Box<dyn Prod<Out = /* Type */>> = Box::new(A); println!("{}", b.get()); }
| ++++++++++++++++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0191`.
Box<dyn Prod<Out = i32>>.- A by-value
selfmethod called on a trait object is E0161. A receiver ofself: Box<Self>is dispatchable - the box is a pointer - but a plain by-value receiver asks the caller to move a value out of the object, whose size is not statically known:
trait Eat { fn eat(self) -> i32; }
struct A;
impl Eat for A { fn eat(self) -> i32 { 9 } }
fn main() { let b: Box<dyn Eat> = Box::new(A); println!("{}", b.eat()); }
$ rustc --edition 2021 trap_by_value.rs -o trap_by_value
error[E0161]: cannot move a value of type `dyn Eat`
--> trap_by_value.rs:4:63
|
4 | fn main() { let b: Box<dyn Eat> = Box::new(A); println!("{}", b.eat()); }
| ^ the size of `dyn Eat` cannot be statically determined
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0161`.
The repair is a pointer receiver - Box<Self>, Rc<Self>, or a reference - which the Reference lists among the dispatchable receiver types.
- A type that does not implement the trait, passed where a trait object is required, is E0277 - the ordinary trait-bound error, not an object-safety error. The trait here is fully dyn compatible; the value is what is wrong:
trait Draw3 { fn draw(&self) -> i32; }
struct B;
fn show(d: &dyn Draw3) { println!("{}", d.draw()); }
fn main() { show(&B); }
$ rustc --edition 2021 trap_bound.rs -o trap_bound
error[E0277]: the trait bound `B: Draw3` is not satisfied
--> trap_bound.rs:4:18
|
4 | fn main() { show(&B); }
| ^^ unsatisfied trait bound
|
help: the trait `Draw3` is not implemented for `B`
--> trap_bound.rs:2:1
|
2 | struct B;
| ^^^^^^^^
help: this trait has no implementations, consider adding one
--> trap_bound.rs:1:1
|
1 | trait Draw3 { fn draw(&self) -> i32; }
| ^^^^^^^^^^^
= note: required for the cast from `&B` to `&dyn Draw3`
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0277`.
The repair is to implement the trait for the type, or pass a type that has it.
- A method the trait does not have is E0599. Trait objects expose exactly the trait's methods - there is no concrete type left to look the method up on:
trait Draw5 { fn draw(&self) -> i32; }
struct A;
impl Draw5 for A { fn draw(&self) -> i32 { 4 } }
fn main() { let b: Box<dyn Draw5> = Box::new(A); println!("{}", b.paint()); }
$ rustc --edition 2021 trap_no_method.rs -o trap_no_method
error[E0599]: no method named `paint` found for struct `Box<dyn Draw5>` in the current scope
--> trap_no_method.rs:4:67
|
4 | fn main() { let b: Box<dyn Draw5> = Box::new(A); println!("{}", b.paint()); }
| ^^^^^ method not found in `Box<dyn Draw5>`
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0599`.
The repair is to call a method the trait declares, or add the method to the trait.
- Moving a concrete value out of a
Box<dyn Trait>is E0308, a plain mismatch - expected the concrete struct, found the trait object. The object has erased the concrete type; that erasure is what it is for:
trait Draw4 { fn draw(&self) -> i32; }
struct A;
impl Draw4 for A { fn draw(&self) -> i32 { 4 } }
fn main() { let b: Box<dyn Draw4> = Box::new(A); let a: A = *b; let _ = a; }
$ rustc --edition 2021 trap_mismatch.rs -o trap_mismatch
error[E0308]: mismatched types
--> trap_mismatch.rs:4:61
|
4 | fn main() { let b: Box<dyn Draw4> = Box::new(A); let a: A = *b; let _ = a; }
| - ^^ expected `A`, found `dyn Draw4`
| |
| expected due to this
|
= note: expected struct `A`
found trait object `dyn Draw4`
= help: `A` implements `Draw4` so you could change the expected type to `Box<dyn Draw4>`
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0308`.
The repair is to keep the value as the trait object, or hold the concrete type from the start when the concrete value is what the program needs.
- Calling an excluded method on a trait object is an error with no code. The
where Self: Sizedbound that makes the second family's repair work removes the method from the object, and calling it there fails with the plain message that the method cannot be invoked on a trait object:
trait Mix2 { fn get(&self) -> i32; fn put<T>(&self, v: T) where Self: Sized; }
struct A;
impl Mix2 for A { fn get(&self) -> i32 { 5 } fn put<T>(&self, _v: T) where Self: Sized {} }
fn main() { let b: Box<dyn Mix2> = Box::new(A); b.put(1); }
$ rustc --edition 2021 trap_call_excluded.rs -o trap_call_excluded
error: the `put` method cannot be invoked on a trait object
--> trap_call_excluded.rs:4:51
|
1 | trait Mix2 { fn get(&self) -> i32; fn put<T>(&self, v: T) where Self: Sized; }
| ----- this has a `Sized` requirement
...
4 | fn main() { let b: Box<dyn Mix2> = Box::new(A); b.put(1); }
| ^^^
error: aborting due to 1 previous error
The repair is to call the method on a concrete value, as the neighbors do, before the value is boxed.
Checklist
- The header checked: E0038 means the trait cannot be a trait object - if the code is E0191, E0161, E0277, E0599, or E0308, or there is no code, the traps name the difference before any edit.
- The note read before editing: its "...because" line names the clause - a
Selfreturn, a generic parameter, an associated constant, aSizedrequirement,Selfas a supertrait parameter, animpl Traitreturn - and the clause picks the repair. - The repair matched to who owns the trait: your own trait can be reshaped or excluded method by method; a standard or third-party trait like
Clonecannot, so its repair is static dispatch or a wrapper trait of your own. - For an excluded method, the call sites checked:
where Self: Sizedremoves the method from the object, so every call throughdynhas to move to a concrete value. - For a restated method, the replacement checked for the same trap in a new form:
Box<Self>is stillSelf; the box has to hold the trait object. - For an associated type, the object type checked: the type must be named on the
dyntype, or the error is E0191, not E0038. - The fixed program run, and its output checked against what the program was meant to print - several repairs compile in more than one form, and the one that preserves the behavior is the program's call, not the compiler's.
Related guides on this site
- E0185 Method Has Self but Trait Does Not Fix
- E0120 Drop on Trait Object or Reference Fix
- E0437 Type Not a Member of Trait Fix
- E0782 Trait Object Needs dyn Fix
Sources
- Rust, Error codes index: E0038 — for the definition of the error as a trait not being allowed as a trait object type, for the vtable account of why, for the Sized, Self-return, generic-method, no-receiver, associated-constant, and supertrait-Self conditions, and for the Self Sized exclusion, the trait-object parameter, the helper method in place of a constant, and the removal of a Sized restriction as repairs.
- The Rust Reference, Traits — for the dyn-compatibility conditions as a list, for dispatchable receivers including Box, Rc, and Arc of Self, for the ban on opaque return types in dispatchable methods, and for explicitly non-dispatchable functions as those with a Self Sized bound.
- Rust, Error codes index: E0191 — for the neighboring error where an associated type was not specified for a trait object, and for specifying the associated type as its repair.
- The Rust Standard Library, Clone — for Clone as a trait with a Sized supertrait whose clone method returns Self, and for clone_from taking a reference to Self.
Keep Exploring
The full Rust hub \u2014 ownership, structs and enums, async, and measured comparisons.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.