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...
  ok(())
}

fn main() {
    let test = "test".to_string();
    tokio::run(make_future(&test));
}

Playground link: https://play.rust-lang.org/?gist=5246458639094d4966d1bd30745f7cc0&version=stable&mode=debug&edition=2015

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/main.rs:13:29
   |
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?

2 Likes

I think this is https://github.com/rust-lang/rust/issues/42940

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:
https://play.rust-lang.org/?gist=bf0f6009ef7ff0ba4ba1b1bc19460b22&version=stable&mode=debug&edition=2015

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

1 Like

A more accurate repro would be https://play.rust-lang.org/?gist=fffa1a99fb9b95eed567096b55eca280&version=stable&mode=debug&edition=2015, which shows the same error.

1 Like

Ah, I see. Thanks!