Skip to content

Suggest flatten over filter(Option::is_some) #11843

Closed
@flip1995

Description

@flip1995

What it does

Checks for usage of filter(Option::is_some) or filter(Result::is_ok) on an Iterator.

This is more succinctly written with just flatten().

Careful: The suggestion must be MaybeIncorrect, as this changes the type of the iterator from Item = Option<T> to Item = T.

good-first-issue instructions: This lint should be quite easy to add as another clippy_lints/src/methods/ lint. All of the parts required to check for this should already be there and can be reused.

Advantage

  • Shorter code
  • Potentially more readable code in following methods in the iterator chain:
    .filter(Option::is_some).map(|x| /*some code*/ x.unwrap() /*some code*/)
    // becomes
    .flatten().map(|x| /*some code*/ x /*some code*/)

Drawbacks

Changes the type of the iterator chain. This will lead to more refactorings required down the chain. But I think in most cases this will benefit the code complexity overall.

Example

v.into_iter().filter(Option::is_some);
v.into_iter().filter(Result::is_ok);

Could be written as:

v.into_iter().flatten();

Playground

Metadata

Metadata

Labels

A-lintArea: New lintsL-complexityLint: Belongs in the complexity lint groupgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions