Skip to content

Function works but non-capturing closure with identical signature fails with strange error #81326

Open
@angelsl

Description

@angelsl

Playground

I'm trying to use the solution suggested for a separate problem here.

The solution works with a coerced function item, but not a closure that is virtually identical.


use std::future::Future;

trait AsyncFn1Arg<'a, Arg: 'a, Ret: 'a> {
    type Fut: Future<Output=Ret> + 'a;
    fn call(&self, arg: Arg) -> Self::Fut;
}

impl<'a, Arg: 'a, Ret: 'a, Fut: Future<Output=Ret> + 'a, F: Fn(Arg) -> Fut> AsyncFn1Arg<'a, Arg, Ret> for F {
    type Fut = Fut;
    fn call(&self, arg: Arg) -> Fut {
        self(arg)
    }
}

async fn f(arg: &i32) {
}

async fn func<F>(f: F)
    where F: for<'a> AsyncFn1Arg<'a, &'a i32, ()>
    {
        let x: i32 = 0;
        f.call(&x).await;
}

fn main() {
    // works
    func(f);
    // fails
    func(|a| f(a));
}

produces

error[E0308]: mismatched types
  --> src/main.rs:29:5
   |
29 |     func(|a| f(a));
   |     ^^^^ lifetime mismatch
   |
   = note: expected type `FnOnce<(&'a i32,)>`
              found type `FnOnce<(&i32,)>`
note: this closure does not fulfill the lifetime requirements
  --> src/main.rs:29:10
   |
29 |     func(|a| f(a));
   |          ^^^^^^^^
note: the lifetime requirement is introduced here
  --> src/main.rs:19:14
   |
19 |     where F: for<'a> AsyncFn1Arg<'a, &'a i32, ()>
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-async-awaitArea: Async & AwaitA-closuresArea: Closures (`|…| { … }`)A-lifetimesArea: Lifetimes / regionsAsyncAwait-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.T-typesRelevant to the types team, which will review and decide on the PR/issue.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