Skip to content

"captured variable cannot escape FnMut closure body" doesn't say which variable escapes #106438

Open
@jyn514

Description

@jyn514

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7118a398f76c37fd88ad80cba70e862e

pub fn run<'s, F>(_: F)
where
    F: FnMut() -> Box<dyn FnMut() + 's>, 
{
    // todo
}

fn foo(f: &mut dyn Fn()) {
    run(move || Box::new(|| {
        // dummy lines to push `f` off the screen
        //
        //
        f();
        //
        //
    }));
}

The current output is:

error: captured variable cannot escape `FnMut` closure body
  --> src/lib.rs:9:17
   |
9  |       run(move || Box::new(|| {
   |  _______________-_^
   | |               |
   | |               inferred to be a `FnMut` closure
10 | |         // dummy lines to push `f` off the screen
11 | |         //
12 | |         //
...  |
15 | |         //
16 | |     }));
   | |______^ 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

Ideally the output should point to f on line 13 to explain that it's the variable that escapes. It would also be nice to more clearly distinguish that it's being returned from the outer closure, not the inner closure, but I'm not sure how to make that better.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-edition-2021Area: The 2021 editionT-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