rust-lang / rust-lang/rust-clippy

map + filter with unwrap on options and results

Open
#15,026 2 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

Given a sequence of Option types like &[Option<T>], users sometimes tend to iterate with filter + map(unwrap) sequence. Instead, they should use .flatten().map() without the unwrap.

Other cases:

  • sequence of Results
  • usage of other "unwrapping" functions like unwrap_or_default, expect, etc
Advantage
  • Faster and cleaner code without panic
Drawbacks

No response

Example
pub fn filter_and_map_options(values: &[Option<i32>]) -> String {
    values
        .iter()
        .filter(|v| v.is_some())
        .map(|v| v.unwrap().to_string())
        .collect::<String>()
}

Could be written as:

pub fn filter_and_map_options(values: &[Option<i32>]) -> String {
    values
        .iter()
        .flatten()
        .map(|v| v.to_string())
        .collect::<String>()
}

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

The issue proposes a Rust Clippy lint for iterator chains that filter options or results and then unwrap, including variants such as unwrap_or_default and expect. No files or tests are named, so first identify the existing lint and test conventions for iterator patterns. Done means the relevant cases are detected and the flatten().map() alternative is supported without false positives.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.