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

manual_unwrap_or_default ignores side effect for None branch

Open crumblingstatue opened this issue 2 years ago • 2 comments

Summary

manual_unwrap_or_default lint's suggestion ignores the side effect(s) present in the None branch.

Reproducer

fn main() {
    let result = match 1u32.checked_div(0) {
        Some(value) => value,
        None => {
            eprintln!("Hello, I'm a side effect");
            0
        },
    };
    eprintln!("{result}");
}
warning: match can be simplified with `.unwrap_or_default()`
 --> src/main.rs:2:18
  |
2 |       let result = match 1u32.checked_div(0) {
  |  __________________^
3 | |         Some(value) => value,
4 | |         None => {
5 | |             eprintln!("Hello, I'm a side effect");
6 | |             0
7 | |         },
8 | |     };
  | |_____^ help: replace it with: `1u32.checked_div(0).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

Clippy makes the side effect disappear with its suggestion.

Version

rustc 1.79.0-nightly (5f2c7d2bf 2024-03-25)
binary: rustc
commit-hash: 5f2c7d2bfd46cad00352ab7cd66242077e2e518c
commit-date: 2024-03-25
host: x86_64-unknown-linux-gnu
release: 1.79.0-nightly
LLVM version: 18.1.2

Additional Labels

No response

crumblingstatue avatar Mar 26 '24 20:03 crumblingstatue

It will make sense to also make sure the comments are not discarded right? just like what has been done in [question_mark], such as:

let result = match 1u32.checked_div(0) {
      Some(value) => value,
      None => {
          // I'd like to keep this comment
          0
      },
  };

Oh, maybe and this, therefore there shouldn't be any comment inside the match expression's span entirely I guess, as they would all get removed by the suggestion.

let result = match 1u32.checked_div(0) {
      Some(value) => value,
      /// I'd like to keep this comment as well
      None => {
          0
      },
  };

@rustbot claim

J-ZhengLi avatar Mar 27 '24 07:03 J-ZhengLi

Related: #12553, #12580

NullSpaceBoy avatar Mar 28 '24 14:03 NullSpaceBoy