-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Open
Labels
A-lintArea: New lintsArea: New lints
Description
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
Result
s - 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>()
}
Metadata
Metadata
Assignees
Labels
A-lintArea: New lintsArea: New lints
Type
Projects
Milestone
Relationships
Development
Select code repository
Activity
matthiaskrgr commentedon Jun 9, 2025
could also use
flatten()
I think?nyurik commentedon Jun 10, 2025
oh, good idea, thanks! I didn't even realize this. Also, I wounder if we should have more lints like these?
iter.filter(|v| v.is_some()).map(...)
- always suggestiter.flatten()
, even if we cannot detect if there is anunwrap
- simply because the chances of user wanting to preserve a sequence ofOption
s are low. Sadly, this is less than certain.map
clearly unwraps the value - high confidenceiter.flatten()
, with the result probably compiling okiter.filter_map(|v| v.map(|v| ...))
- treat it the same as above