Type alias doesn't work with `dyn Trait`

⚓ rust    📅 2025-05-30    👤 surdeus    👁️ 3      

surdeus

I encountered a lifetime issue when using type alias with dyn Trait. Here's the simplified code:

trait Foo {
    fn work(&self, arg: &impl Bar);
}
trait Bar {}
type DynBar = dyn Bar;

impl<F> Foo for F
where
 // F: Fn(&dyn Bar),
    F: Fn(&DynBar),
{
    fn work(&self, arg: &impl Bar) {
        self(arg)
    }
}

The compiler say:

error[E0310]: the parameter type `impl Bar` may not live long enough
  --> src\main.rs:14:14
   |
14 |         self(arg)
   |              ^^^
   |              |
   |              the parameter type `impl Bar` must be valid for the static lifetime...
   |              ...so that the type `impl Bar` will meet its required lifetime bounds
   |
help: consider adding an explicit lifetime bound
   |
13 |     fn work(&self, arg: &impl Bar + 'static) {
   |                                   +++++++++

What's going on? Shouldn't type aliases be just simple substitutions? If the type alias is not used, it will compile fine.

5 posts - 3 participants

Read full topic

🏷️ rust_feed