Skip to content

Suggest replacing filter-for-some-and-unwrap with .flatten #6061

Closed
@NoraCodes

Description

@NoraCodes

What it does

Suggests replacing code that filters with Option::is_some and then maps Option::unwrap with .flatten() which does the same thing due to Option implementing IntoIterator.

Categories (optional)

  • Kind: clippy::style

Advantage

It is one function call fewer and makes it clearer what is happening - one level of indirection is being removed. In addition, many codebases want to eliminate all possible panic sources, of which Option::unwrap is one, although in this case it is statically known not to panic.

Drawbacks

None.

Example

fn odds_out(x: i32) -> Option<i32> { if x % 2 == 0 { Some(x) } else { None } }
let evens: Vec<_> = myints.iter().map(odds_out).filter(Option::is_some).map(Option::unwrap).collect();

Could be written as:

fn odds_out(x: i32) -> Option<i32> { if x % 2 == 0 { Some(x) } else { None } }
let evens: Vec<_> = myints.iter().map(odds_out).flatten().collect();

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesL-suggestionLint: Improving, adding or fixing lint suggestionsgood 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