Decouple generic argument lifetime from impl Trait return value lifetime

here's a minimized example

trait Input {}
impl<'a> Input for &'a str {}

fn create_fut_bad<'r, 'i, I: Input + 'i>(input: I) -> impl Future<Output = String> + 'r {
    async { String::new() }
}
fn bad() -> impl Future<Output = String> {
    let s = String::new();
    create_fut_bad(s.as_str()) // `s` does not live long enough
}

the function create_fut_bad creates a future which is obviously invariant to the input argument lifetime, but I'm having trouble somehow encoding it into the function signature.

If the input argument is not generic, everything is fine. E.g.:

fn create_fut_good<'r, 'i>(input: &'i str) -> impl Future<Output = String> + 'r {
    async { String::new() }
}
fn good() -> impl Future<Output = String> {
    let s = String::new();
    create_fut_good(s.as_str())
}

I tried HRTB, adding lifetime argument to Input trait, taking a reference to I ... nothing seems to help.
Is there a way to encode the lifetime invariance?

Your attempts aren't really about variance as written; you're trying to return some unrelated lifetime, any related lifetime, which is basically going to require returning something with a 'static lifetime.

A returned impl Trait captures all generic type parameters/inputs, so if you want to return a 'static one, you need a 'static bound on them... which won't work with local borrows.

You'd need to define your own opaque type, which is not yet possible on stable, and apparently buggy for this use case on nightly. Not sure if there's an open issue for this.

Edit: after a little playing, it's actually the async block doing the capturing despite being separate from the function. One can work around it.

Thanks a lot for looking into this. I can at least stop banging my head against the wall :slight_smile:.
My use case is a bit more complicated and type_alias_impl_trait feature does not seem to cut it just yet. (error: non-defining opaque type use in defining scope :person_shrugging:)
I'll try to create a specific type implementing Future where I can control the lifetime annotations an return that instead.
Again, thank you

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.