This error occurs because Rust 2018 and later require the dyn keyword to explicitly mark a type as a dynamic trait object, replacing the old bare trait syntax. You must add dyn before the trait name whenever you use it in a type context like Box<Trait> or &Trait.
Here is the corrected syntax for common scenarios:
// ❌ Old syntax (pre-2018) or invalid in modern Rust
let obj: Box<Display> = Box::new(5);
// ✅ Correct syntax
let obj: Box<dyn Display> = Box::new(5);
// Also applies to references
fn print_ref(item: &dyn Display) {
println!("{}", item);
}
If you are defining a function that takes a trait object as an argument or return type, the dyn keyword is mandatory. For example, if you previously wrote fn process(x: &Iterator), it will now fail. You must change it to fn process(x: &dyn Iterator). This distinction is crucial because Rust needs to know if you are referring to a concrete type that implements a trait (like Vec<i32>) or a dynamic object where the concrete type is erased at compile time.
You will also encounter this error when using trait objects in generic collections or as fields in structs. Consider this struct definition:
// ❌ Error: trait objects must include `dyn` keyword
struct Handler {
callback: Box<ToString>,
}
// ✅ Fixed
struct Handler {
callback: Box<dyn ToString>,
}
If you are using an older edition of Rust (2015), the compiler might allow the bare trait syntax, but it is deprecated and will cause issues if you upgrade your project. The dyn keyword was introduced to make the distinction between static and dynamic dispatch clearer. Without it, the compiler cannot determine if you intend to use a generic type parameter (static dispatch) or a heap-allocated trait object (dynamic dispatch).
To fix this globally in a codebase, search for patterns like Box<TraitName> or &TraitName where TraitName is a trait, not a struct, and prepend dyn. If you are using cargo fix, it often automatically applies this change for you, but manual verification is recommended to ensure the logic remains sound. Remember that dyn is only needed for trait objects; if you are using generics with impl Trait or T: Trait, you do not use dyn there.