rust-lang / rust-lang/rust-clippy

suggest `filter`, `map` instead of `if let Some(..) { Some() } else { None }` on Options?

Open
#10,078 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

I was looking at some rustc code and noticed some if let Some(..) code where we would map back to Some(x) or None in the end and wondered if it would make sense to use filter and map here instead

Lint Name

not sure

Category

pedantic

Advantage

Code is shorter but I am not sure if its easier to understand

Drawbacks

Not sure if readability is actually improved.

Example
fn main() {
    let s = String::from("opt-level=2");
    let i = 42; // whatever

    let z = if let Some("opt-level") = s.split('=').next() { Some(i) } else { None };
    dbg!(z);
}

Could be written as:

fn main() {
    let s = String::from("opt-level=2");
    let i = 42; // whatever

    let z = s.split('=').next().filter(|x| x == &"opt-level").map(|x| i);
    dbg!(z);
}

(we have an Option here so we can filter to None instead of if let .. else { None } and we can map(|x| i) instead of if let .. { Some(i) })

I think the second example looks a bit more streamlined and might be easier to understand it doesn't have all the if let else control flow, on the other hand, the explicit control flow might make the code better to understand as well (explicit is better than implicit etc..)

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

No source file, test, or lint entry point is identified. Start by comparing the two Rust examples and determining whether this transformation should be a Clippy lint, including its scope and readability tradeoffs; done requires a decided lint design and corresponding implementation and tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.