rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

map + filter with unwrap on options and results

Open nyurik opened this issue 4 months ago • 2 comments

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>()
}

nyurik avatar Jun 09 '25 17:06 nyurik