Trait with method returning Self with updated lifetime

⚓ rust    📅 2025-04-25    👤 surdeus    👁️ 2      

surdeus

I'm trying to define a trait with a method that consumes an implementation (say: Impl<'this>) of the trait and is supposed to produce a new instance of the same implementation (say: Impl<'next>) with an updated lifetime.

trait TraitWithLifetime<'this> {
    fn switch_to_next<'next>(
        self,
        next: Something<'next>,
    // How can I return Self with an updated lifetime?
    // - Self<'next> isn't allowed.
    // - impl TraitWithLifetime<'next> is not strong enough as
    //   I need to save the result in a struct, ie. I need a specific
    //   return type.
    // - Self + 'next doesn't work because it will return Impl<'this>
    //   rather than Impl<'next>.
    // - Let Impl return Impl<'next> while the trait defines
    //   impl TraitWithLifetime<'next> (refined return type) doesn't
    //   work because the caller would then have to be aware of
    //   the specific implementation.
    ) -> ???;
}

The trait is intended to be used like this:

struct Impl<'a> {...}
impl <'a> TraitWithLifetime<'a> for Impl<'a> {...}

fn switch<'this, 'next> (
    impl_this: Impl<'this>,
    next: Something<'next>,
) -> Impl<'next> {
    impl_this.switch_to_next(next)
}

Any ideas?

3 posts - 2 participants

Read full topic

🏷️ rust_feed