Skip to content

manual_inspect suggestion breaks mutating code #13185

@Swatinem

Description

@Swatinem

Summary

Here is a playground link: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=e4fad507e221cf2e8540575031233165

The suggestion leads to broken code which does not compile:

error[E0594]: cannot assign to `a.a`, which is behind a `&` reference
  --> src/main.rs:18:9
   |
17 |     let ref_mut_opt = opt.as_mut().inspect(|a| {
   |                                             - consider changing this binding's type to be: `&mut &mut A`
18 |         a.a += 123;
   |         ^^^^^^^^^^ `a` is a `&` reference, so the data it refers to cannot be written

Using inspect, I end up with & &mut A, and I can’t seem to be able to mutate things through that reference.
Changing the signature as suggested in the second compiler error is also not possible.

Lint Name

manual_inspect

Reproducer

I tried this code:

#[derive(Debug)]
struct A {
    a: u32,
}

fn main() {
    // warns but works:
    let mut opt = Some(A { a: 123 });
    let ref_mut_opt = opt.as_mut().map(|a| {
        a.a += 123;
        a
    });
    dbg!(ref_mut_opt);
}

I saw this happen:

warning: using `map` over `inspect`
 --> src/main.rs:9:36
  |
9 |     let ref_mut_opt = opt.as_mut().map(|a| {
  |                                    ^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_inspect
  = note: `#[warn(clippy::manual_inspect)]` on by default
help: try
  |
9 ~     let ref_mut_opt = opt.as_mut().inspect(|a| {
10~         a.a += 123;
  |

Version

rustc 1.82.0-nightly (7120fdac7 2024-07-25)
binary: rustc
commit-hash: 7120fdac7a6e55a5e4b606256042890b36067052
commit-date: 2024-07-25
host: x86_64-apple-darwin
release: 1.82.0-nightly
LLVM version: 18.1.7

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions