Skip to content

async move closure owning Fn and calling it #128516

Closed
@ChayimFriedman2

Description

@ChayimFriedman2

I tried this code (https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=1062a9d9bd18705abc0f2109c7df7ef3):

#![feature(async_closure)]

fn wrapper(f: impl Fn()) -> impl async Fn(String) {
    async move |_| f()
}

I expected to see this happen: this compiles successfully. In my understanding of async closures, the closure should own f but its returned future should borrow it from the closure, leading to no error. Furthermore, if all of returned closure's arguments are Copy, this compiles successfully - I don't think the arguments' types should change anything.

Instead, this happened: it errors with:

error[E0507]: cannot move out of `f` which is behind a shared reference
 --> src/lib.rs:4:5
  |
4 |     async move |_| f()
  |     ^^^^^^^^^^^^^^ -
  |     |              |
  |     |              variable moved due to use in coroutine
  |     |              move occurs because `f` has type `impl Fn()`, which does not implement the `Copy` trait
  |     `f` is moved here
  |
help: if `impl Fn()` implemented `Clone`, you could clone the value
 --> src/lib.rs:3:15
  |
3 | fn wrapper(f: impl Fn()) -> impl async Fn(String) {
  |               ^^^^^^^^^ consider constraining this type parameter with `Clone`
4 |     async move |_| f()
  |                    - you could clone this value

For more information about this error, try `rustc --explain E0507`.

@rustbot label +F-async_closure

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions