Closed
Description
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();