rust-lang / rust-lang/rust-clippy

New lint: `invariant_collect_option`

Open
#6,579 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint E-medium L-complexity
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.