rust-lang / rust-lang/rust-clippy
New lint: `invariant_collect_option`
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
Checks for use of collect::<Option<_>>() where the result is always Some or always None. If the iterator always contains None, then the collect will always yield None and is pointless. If the iterator items are always Some, then the collect will always yield Some and can most likely be simplified.
Detection of these cases could iteratively improve over time, but we can start with the example below.
Categories (optional)
- Kind: complexity
Drawbacks
None.
Example
(0..5).map(|n| Some(n + 1)).collect::<Option<Vec<u32>>>();
Could be written as:
(0..5).map(|n| n + 1).collect::<Vec<u32>>();
The lint could work with filter or take (and more?) operations between map and collect.
It is probably too difficult to provide a specific suggestion to fix this lint. The user will have to change not only the iterator, but the usage of the collect output.
The programmer may have a misconception that None will be returned if the iterator is empty. This may be addressed in the lint output.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the issue's example and review existing Rust Clippy lint implementations and test conventions; no specific source file or test is named. Define detection for iterator chains whose Option items are always Some or None, and verify the lint reports the example without requiring an automatic suggestion.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100