Skip to content

Confusing output when passing a FnMut closure via non-mut reference #118843

Open
@Lexicality

Description

@Lexicality

Code

fn main() {
    let mut i = 0;
    let mut func = |x: usize| {
        i += x;
    };
    (0..100).for_each(&func);
}

Current output

Compiling playground v0.0.1 (/playground)
error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut`
   --> src/main.rs:3:20
    |
3   |     let mut func = |x: usize| {
    |                    ^^^^^^^^^^ this closure implements `FnMut`, not `Fn`
4   |         i += x;
    |         - closure is `FnMut` because it mutates the variable `i` here
5   |     };
6   |     (0..100).for_each(&func);
    |              --------  ---- the requirement to implement `Fn` derives from here
    |              |
    |              required by a bound introduced by this call
    |
    = note: required for `&{closure@src/main.rs:3:20: 3:30}` to implement `FnMut<(usize,)>`
note: required by a bound in `for_each`
   --> /playground/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:850:12
    |
847 |     fn for_each<F>(self, f: F)
    |        -------- required by a bound in this associated function
...
850 |         F: FnMut(Self::Item),
    |            ^^^^^^^^^^^^^^^^^ required by this bound in `Iterator::for_each`

For more information about this error, try `rustc --explain E0525`.
error: could not compile `playground` (bin "playground") due to previous error

Desired output

Something pointing out the closure reference should be `&mut`

Rationale and extra context

Highlighting the bound trait FnMut is particularly confusing

Other cases

No response

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-type-systemArea: Type systemD-confusingDiagnostics: Confusing error or lint that should be reworked.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types 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