Skip to content

Which captured variable cannot escape FnMut closure body? #69446

Closed
@akshayknarayan

Description

@akshayknarayan

Related to #31752. cc @jonhoo

This code does not compile (playground):

extern crate futures_util; // 0.3.4
use futures_util::stream::StreamExt;

struct Foo;
impl Foo {
    fn foo(&mut self) { }
}

fn main() {
    let mut x = Foo;
    futures_util::stream::iter(0..1).for_each(move |_| {
        async { x.foo(); }
    });
}

due to:

error: captured variable cannot escape `FnMut` closure body
  --> src/main.rs:12:9
   |
11 |     futures_util::stream::iter(0..1).for_each(move |_| {
   |                                                      - inferred to be a `FnMut` closure
12 |         async { x.foo(); }
   |         ^^^^^^^^^^^^^^^^^^ returns a reference to a captured variable which escapes the closure body
   |
   = note: `FnMut` closures only have access to their captured variables while they are executing...
   = note: ...therefore, they cannot allow references to captured variables to escape

It would be helpful if the compiler said which captured variable escaped the closure (in the example, it is x, but this is not always clear if there are many captured variables).

Metadata

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.C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.P-mediumMedium priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions