rust-clippy
rust-clippy copied to clipboard
map + filter with unwrap on options and results
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>()
}