rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

 `manual_unwrap_or_default` triggers on code with mutation

Open Ltrlg opened this issue 2 years ago • 2 comments

Summary

 manual_unwrap_or_default seems to be assuming that the unwrapped value is not mutated.

Lint Name

manual_unwrap_or_default

Reproducer

I tried this code:

pub fn unwrap_with_suffix(unsuffixed_opt: Option<String>) -> String {
    if let Some(mut res) = unsuffixed_opt {
        res.push_str("_suffixed");
        res
    } else {
        String::new()
    }
}

I saw this happen:

warning: if let can be simplified with `.unwrap_or_default()`
 --> src/lib.rs:2:5
  |
2 | /     if let Some(mut res) = unsuffixed_opt {
3 | |         res.push_str("_suffixed");
4 | |         res
5 | |     } else {
6 | |         String::new()
7 | |     }
  | |_____^ help: replace it with: `unsuffixed_opt.unwrap_or_default()`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_unwrap_or_default
  = note: `#[warn(clippy::manual_unwrap_or_default)]` on by default

I expected to see this happen:

No warning, as the proposed replacement is not equivalent.

Version

rustc 1.79.0-nightly (0824b300e 2024-03-24)
binary: rustc
commit-hash: 0824b300eb0dae5d9ed59719d3f2732016683d66
commit-date: 2024-03-24
host: x86_64-unknown-linux-gnu
release: 1.79.0-nightly
LLVM version: 18.1.2

Additional Labels

No response

Ltrlg avatar Mar 25 '24 08:03 Ltrlg

@rustbot claim

NullSpaceBoy avatar Mar 28 '24 04:03 NullSpaceBoy

This has been fixed in https://github.com/rust-lang/rust-clippy/pull/12579.

NullSpaceBoy avatar Apr 09 '24 05:04 NullSpaceBoy