Skip to content

unhelpful error when missing move in nested closure #95079

Closed
@lcnr

Description

@lcnr

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1cb8bf9552639abd2a8178105cd3f001

fn foo(s: &str) -> impl Iterator<Item = String> + '_ {
    None.into_iter()
        .flat_map(move |()| s.chars().map(|c| format!("{}{}", c, s)))
}

The current output is:

error: captured variable cannot escape `FnMut` closure body
 --> src/lib.rs:3:29
  |
1 | fn foo(s: &str) -> impl Iterator<Item = String> + '_ {
  |        - variable defined here
2 |     None.into_iter()
3 |         .flat_map(move |()| s.chars().map(|c| format!("{}{}", c, s)))
  |                           - -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |                           | |
  |                           | returns a reference to a captured variable which escapes the closure body
  |                           | variable captured here
  |                           inferred to be a `FnMut` closure
  |
  = 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: could not compile `playground` due to previous error

The actually needed fix here is the following, which should ideally be recommended

fn foo(s: &str) -> impl Iterator<Item = String> + '_ {
    None.into_iter()
        .flat_map(move |()| s.chars().map(move |c| format!("{}{}", c, s)))
}

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-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