Lifetime issue with AsRef argument with 'static return type

I’m having some lifetime issues I don’t fully understand when working with a function that takes in an AsRef<str> and returns a Future with a 'static lifetime. Here is a minimal example of the general situation:

extern crate futures;
extern crate tokio;

use futures::{Future, future::ok};

fn make_future(_s: impl AsRef<str>) -> impl Future<Item = (), Error = ()> + 'static {
  // Do stuff...

fn main() {
    let test = "test".to_string();

Playground link:

In this example, you can imagine that make_future() is a function that takes an argument of some type that implements AsRef<str>, calls .as_ref() on it, and based on the borrowed value constructs some Future which does not hold any references (and is thus 'static).

The example above fails to compile:

error[E0597]: `test` does not live long enough
  --> src/
13 |     tokio::run(make_future(&test));
   |                             ^^^^ borrowed value does not live long enough
14 | }
   | - borrowed value only lives until here
   = note: borrowed value must be valid for the static lifetime...

I don’t understand why I’m getting this error, because it doesn’t seem like the function signature should place any bounds on the lifetime of _s (the only trait bound present is AsRef<str>. I figured this might have something to do with lifetime elision, but changing the type of _s to &str causes the code to compile successfully.

Does anyone know what is going on here?


I think this is

1 Like

Hm, definitely looks like this is what it could be.

What’s weird though is I can’t repro the issue using impl Iterator + 'static instead of impl Future + 'static:

(Based on the linked issue, I’d expect this to also fail.)

1 Like

A more accurate repro would be, which shows the same error.

1 Like

Ah, I see. Thanks!