Skip to content

Unclear lifetime error in closure producing a future #74497

Open
@95th

Description

@95th

Code:

use std::future::Future;

pub async fn bar() {
    foo(|x| baz(x)).await;
}

pub async fn baz(x: &u8) -> bool {
    if *x == 1 {
        false
    } else {
        true
    }
}

pub async fn foo<F, T>(f: F) -> bool
where
    F: Fn(&u8) -> T,
    T: Future<Output = bool>,
{
    f(&32).await
}

produces following error:

error: lifetime may not live long enough
 --> src/lib.rs:4:13
  |
4 |     foo(|x| baz(x)).await;
  |          -- ^^^^^^ returning this value requires that `'1` must outlive `'2`
  |          ||
  |          |return type of closure is impl std::future::Future
  |          has type `&'1 u8`

Is this error correct? If yes, why?

following also doesn't work:

pub async fn bar() {
    foo(baz).await;
}

error (still not clear):

error[E0271]: type mismatch resolving `for<'r> <for<'_> fn(&u8) -> impl std::future::Future {baz} as std::ops::FnOnce<(&'r u8,)>>::Output == _`
  --> src/lib.rs:4:5
   |
4  |     foo(baz).await;
   |     ^^^ expected bound lifetime parameter, found concrete lifetime
...
15 | pub async fn foo<F, T>(f: F) -> bool
   |              --- required by a bound in this
16 | where
17 |     F: Fn(&u8) -> T,
   |                   - required by this bound in `foo`

meta:

$ rustc --version --verbose
rustc 1.45.0 (5c1f21c3b 2020-07-13)
binary: rustc
commit-hash: 5c1f21c3b82297671ad3ae1e8c942d2ca92e84f2
commit-date: 2020-07-13
host: x86_64-unknown-linux-gnu
release: 1.45.0
LLVM version: 10.0

Metadata

Metadata

Labels

A-async-awaitArea: Async & AwaitA-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsAsyncAwait-PolishAsync-await issues that are part of the "polish" areaAsyncAwait-TriagedAsync-await issues that have been triaged during a working group meeting.C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

Status

In progress (current sprint)

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions