rust-lang / rust-lang/rust-clippy

unnecessary_unwrap: should not trigger if the `is_some` is just part of the conditional

Open
#4,530 4 comments 7 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-enhancement L-suggestion
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

unnecessary_unwrap recommends that foo.is_some() in a conditional followed by foo.unwrap() should be replaced by an if let. That is usually good advice, however, if the is_some is just part of the conditional, then the only way to use if let is with nested ifs.

E.g.,

if some_condition && foo.is_some() {
    let foo = foo.unwrap();
    ...
}

can only be rewritten as

if some_condition {
    if let Some(foo) = foo {
        ...
    }
}

which is not much of an improvement (and arguably no improvement at all). (In this case, using match might be better, but in some more complex examples it is not possible).

I would much prefer is unnecessary_unwrap only triggered when it was possible to rewrite exactly using a single if let or match.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the unnecessary_unwrap lint implementation and its tests in rust-clippy. Reproduce the issue with the some_condition && foo.is_some() example, then compare its behavior with a standalone conditional. Done means the lint avoids recommending a rewrite when is_some() is only part of the condition, while preserving the intended recommendation for directly rewritable cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.