Skip to content

returning a future from a function with an impl Trait argument references that argument even if not used in the future, causing lifetime errors #125341

Closed
@pushrax

Description

@pushrax

I minimized an error I encountered into this reproduction: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=85de243a39f64d49d42939066a2a824c

use std::future::Future;

fn fn2(_unused: impl AsRef<[u64]>) -> impl Future<Output = ()> {
    async move {}
}

fn fn1() -> impl Future<Output = ()> {
    let v = vec![1];
    fn2(&v)
}

#[tokio::main]
async fn main() {
    fn1().await;
}

This should compile.

Instead, this happened:

error[E0597]: `v` does not live long enough
  --> src/main.rs:9:9
   |
8  |     let v = vec![1];
   |         - binding `v` declared here
9  |     fn2(&v)
   |     ----^^-
   |     |   |
   |     |   borrowed value does not live long enough
   |     argument requires that `v` is borrowed for `'static`
10 | }
   | - `v` dropped here while still borrowed

The function argument is unused and it doesn't make sense that it should be borrowed for 'static.

If the impl AsRef<[u64]> argument is changed to &[u64] the snippet compiles fine. It seems like any impl Trait argument passed by value will cause the issue.

In the original non-minimized code, the argument wasn't unused, but only used outside the returned future.

Meta

repros on stable as well as latest nightly (1.80.0-nightly 2024-05-19 d84b903)

cc @morgangallant

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.A-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.F-precise_capturing`#![feature(precise_capturing)]`WG-asyncWorking group: Async & await

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions