rust-lang / rust-lang/rust-clippy

New lint: map_unwrap_or_bool

Open
#5,895 5 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

This lint discourages a less readable idiom when checking an operation which returns an Option<T> chained with a boolean predicate.

My main motivation is to avoid a bad habit of mine while I was still learning all the parts of the APIs. I imagine I am not the only one who learned it.

Categories
  • Kind: clippy::pedantic

What is the advantage of the recommended code over the original code

  • Makes the intention clearer
  • Uses a function that is literally designed for this
  • Allows additional access to the returned value, such as let Some(...) clauses
Drawbacks

Could be superseded by rust-lang/rust#75298

Example
fn main() {
    let https_proxy: Option<String> = std::env::var("HTTPS_PROXY").ok();

    if https_proxy.map(|v| v.starts_with("https://")).unwrap_or(false) {
        eprintln!("You have an HTTPS proxy set in the environment");
    } else {
        eprintln!("You do not have an HTTPS proxy set in the environment");
    }
}

Could be written as:

fn main() {
    let https_proxy: Option<String> = std::env::var("HTTPS_PROXY").ok();

    if https_proxy.filter(|v| v.starts_with("https://")).is_some() {
        eprintln!("You have an HTTPS proxy set in the environment");
    } else {
        eprintln!("You do not have an HTTPS proxy set in the environment");
    }
}

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

Begin by finding how existing Rust Clippy lints are registered and tested, then compare their handling of Option predicates with the issue's map(...).unwrap_or(false) example. Done means a clippy::pedantic lint named map_unwrap_or_bool recognizes the described idiom, suggests filter(...).is_some(), and covers the behavior with tests.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.