rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.46k stars 1.55k forks source link

`unwrap_used` lint should check `Option::is_some` #13450

Open stoneman258 opened 1 month ago

stoneman258 commented 1 month ago

Summary

I've encountered an issue with the linting for unwrap_used in my codebase. The lint should check Option::is_some, like unnecessary_unwrap

Lint Name

clippy::unwrap-used

Reproducer

I tried this code:

pub fn extract(option: Option<usize>)->usize {
    if option.is_some() {
        return option.unwrap();
    }
    0
}

I tried this command:

cargo clippy -- -A clippy::all -W clippy::unwrap_used  

I expected to see this happen: No warning. Instead, this happened: option.unwrap() is reported.

Version

rustc 1.81.0-nightly (4bc39f028 2024-06-26) binary: rustc commit-hash: 4bc39f028d14c24b04dd17dc425432c6ec354536 commit-date: 2024-06-26 host: x86_64-unknown-linux-gnu release: 1.81.0-nightly LLVM version: 18.1.7

samueltardieu commented 1 month ago

unwrap_used is a restriction lint, for projects in which the use of .unwrap() is discouraged or forbidden. I'm not sure I understand why you think it should not warn here, as .unwrap() is definitely used, even though it is safe.

Note that the use of .is_some() followed by .unwrap() can be avoided by writing:

    if let Some(o) = option {
        return o;
    }

or, in your example, with option.unwrap_or_default() but that cannot be generalized.