rust-lang / rust-lang/rust-clippy

Suggest extend over for_each for element insertion

Open
#8,169 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

The lint should detect/convert code which uses a .for_each containing a single .insert into an .extend call.

Lint Name

manual_extend

Category

style

Advantage

The code becomes much cleaner and easier to understand.

Mentally, I read the first example as follows:

  • Get all keys from self.state_machine_info.det_states
  • For each key
    • Insert it in states, but first clone the key.

The second example though:

  • Extend states
  • Using the cloned keys from self.state_machine_info.det_states
Drawbacks

I know that not everyone will read it as I will, however the second approach feels much more in-line with "proper" Rust.

Example

In my typestate macro I have the following code:

let mut states = HashSet::new();
self.state_machine_info.det_states.keys().for_each(|k| {
    states.insert(k.clone());
});
self.state_machine_info
    .non_det_transitions
    .keys()
    .for_each(|k| {
        states.insert(k.clone());
    });

Which becomes much cleaner when written like:

let mut states = HashSet::new();
states.extend(
    self.state_machine_info.det_states.keys().cloned()
);
states.extend(
    self.state_machine_info.non_det_transitions.keys().cloned()
);

https://github.com/rustype/typestate-rs/blob/83b0ef0a6dbd1658c283ec45be0ad611e73e8ff1/typestate-proc-macro/src/visitors/transition.rs#L99-L108

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 manual_extend lint name and the Rust example linked in the issue, focusing on the single-insert .for_each pattern. Define the supported transformation from the first example to the .extend form, then verify the lint’s suggested output and behavior with representative cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.