Rust's dyn compatibility (formerly 'object safety') determines whether a trait can be used as a trait object with `dyn Trait`. A trait is not dyn compatible when it has methods that return `Self`, lack a receiver, or have generic type parameters — because the vtable-based dynamic dispatch system requires stable, concrete function signatures at compile time. Four fixes are covered with tradeoffs: (1) use generics instead of trait objects for compile-time dispatch, (2) add `where Self: Sized` to opt problematic methods out of dispatch, (3) return `Box<dyn Trait>` instead of `Self`, or (4) split the trait into two focused traits. A modern gotcha is that `async fn` in traits also breaks dyn compatibility, with workarounds including `async-trait` and `dynosaur` crates. The post also includes a full reference table of dyn compatibility rules and a historical timeline of how the concept evolved in Rust.

17m read timeFrom corrode.dev
Post cover image
Table of contents
The Error MessageWhat’s going on?How To Fix ItWhat’s Going On Under the Hood?Summary
1.3K Impressions