Skip to content

Nested closures give suboptimal move suggestion #64008

@oli-obk

Description

@oli-obk

The following code needs a move on the map closure, but the suggestion first tells us to add it to the flat_map closure. After following that suggestion, the next error will tell us to put it on the map closure. This terminates correctly, but should suggest the final thing immediately. Note that with many nested levels of closures, there will be one error-fix-recompile cycle per nested closure until we get it working.

pub struct X;

pub fn foo<'a>(
    bar: &'a X,
) -> impl Iterator<Item = ()> + 'a {
    Some(()).iter().flat_map(|()| {
        Some(()).iter().map(|()| { bar; })
    })
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error: captured variable cannot escape `FnMut` closure body
 --> src/lib.rs:7:9
  |
6 |     Some(()).iter().flat_map(move |()| {
  |                                      - inferred to be a `FnMut` closure
7 |         Some(()).iter().map(|()| { bar; })
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 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

error: aborting due to previous error

error: Could not compile `playground`.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsP-lowLow 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