How to add lifetime bounds for trait method returning dyn trait object?

The dyn-applicability lifetime is covariant and can apply during coercion in surprising ways. However, here we're dealing with trait objects buried too deep into a a struct to be coerced, so as far as I'm aware, the lifetime is invariant behind the &mut here as per normal.

So e.g. this doesn't work:

trait Foo<'x> {
    fn bars(&mut self) -> &mut Vec<Box<dyn Bar + '_>>;
}

impl<'x> Foo<'x> for Foo1<'static> {
    fn bars(&mut self) -> &mut Vec<Box<dyn Bar + '_>> {
        &mut self.bars
    }
}

An associated type might make this work without a lifetime on the trait, though add_bar could end up less capable or less ergonomic. Not enough context for me to have an opinion on the best direction, though. In general this question looks like an attempt to work around the lack of "fields in traits".

1 Like