Skip to content

Strange error message when trying to call a function that takes a closure that returns a future #123717

Open
@tljubej-tbtl

Description

Code

use std::future::Future;

fn bar<Fn, Res>(x: &i32, function: Fn) -> Res
where
    Res: Future<Output = i32>,
    Fn: FnOnce(&i32) -> Res,
{
    function(x)
}

async fn foo(x: &i32) -> i32 {
    x + 1
}

fn main() {
    bar(&1, foo);
}

Current output

error[E0308]: mismatched types
  --> lifetime-error-minimal-example/src/main.rs:16:5
   |
16 |     bar(&1, foo);
   |     ^^^^^^^^^^^^ one type is more general than the other
   |
   = note: expected opaque type `impl for<'a> Future<Output = i32>`
              found opaque type `impl Future<Output = i32>`
   = help: consider `await`ing on both `Future`s
   = note: distinct uses of `impl Trait` result in different opaque types
note: the lifetime requirement is introduced here
  --> lifetime-error-minimal-example/src/main.rs:6:25
   |
6  |     Fn: FnOnce(&i32) -> Res,
   |                         ^^^

For more information about this error, try `rustc --explain E0308`.
error: could not compile `lifetime-error-minimal-example` (bin "lifetime-error-minimal-example") due to 1 previous error

Desired output

The compiler should somehow warn me that I need to constrain the lifetime of `Res` to the lifetime of the `&i32`.

Rationale and extra context

If the main function looks like this:

fn main() {
    bar(&1, |x| foo(x));
}

The error message becomes more clear and closer to what I'd expect:

error: lifetime may not live long enough
  --> lifetime-error-minimal-example/src/main.rs:16:17
   |
16 |     bar(&1, |x| foo(x));
   |              -- ^^^^^^ returning this value requires that `'1` must outlive `'2`
   |              ||
   |              |return type of closure `impl Future<Output = i32>` contains a lifetime `'2`
   |              has type `&'1 i32`

Other cases

No response

Rust Version

rustc 1.77.2 (25ef9e3d8 2024-04-09)
binary: rustc
commit-hash: 25ef9e3d85d934b27d9dada2f9dd52b1dc63bb04
commit-date: 2024-04-09
host: aarch64-apple-darwin
release: 1.77.2
LLVM version: 17.0.6

Anything else?

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-async-awaitArea: Async & AwaitA-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsAsyncAwait-TriagedAsync-await issues that have been triaged during a working group meeting.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.WG-asyncWorking group: Async & awaitfixed-by-async-closuresFixed by `#![feature(async_closure)]`

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions