Skip to content

async/await: cannot move out of captured variable in an Fn closure #59971

Open
@leinlawun

Description

@leinlawun

Hello,
recently faced with strange behavior, please comment, is this a bug, or not?
Compiler version: 1.35.0-nightly 2019-04-12 99da733

#![feature(futures_api, async_await, await_macro)]

use std::future::Future;

struct Task<T> {
    task: T,
}

impl<T> Task<T>
where
    T: Fn(),
{
    fn new(task: T) -> Self {
        Self { task }
    }

    fn execute(&self) {
        (self.task)();
    }
}

struct AsyncTask<T> {
    task: T,
}

impl<T, F> AsyncTask<T>
where
    T: Fn() -> F,
    F: Future<Output = ()>,
{
    fn new(task: T) -> Self {
        Self { task }
    }

    async fn execute(&self) {
        await!((self.task)());
    }
}

fn main() {
    let string = "Hello, World!".to_string();
    let _task = Task::new(move || {
        println!("{}", string);
    });

    let string = "Hello, World!".to_string();
    let _async_task = AsyncTask::new(async move || {
        println!("{}", string);
    });
}

(Playground)
(Updated Playground

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0507]: cannot move out of captured variable in an `Fn` closure
  --> src/main.rs:47:52
   |
46 |       let string = "Hello, World!".to_string();
   |           ------ captured outer variable
47 |       let _async_task = AsyncTask::new(async move || {
   |  ____________________________________________________^
48 | |         println!("{}", string);
49 | |     });
   | |_____^ cannot move out of captured variable in an `Fn` closure

error: aborting due to previous errors

For more information about this error, try `rustc --explain E0507`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-async-awaitArea: Async & AwaitA-closuresArea: Closures (`|…| { … }`)AsyncAwait-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.fixed-by-async-closuresFixed by `#![feature(async_closure)]`requires-nightlyThis issue requires a nightly compiler in some way.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions