rust-lang / rust-lang/rust-clippy

Suggest zip + repeat_n instead of loop + clone

Open
#16,291 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

Using zip + repeat_n instead of loop + clone, we can reduce one unnecessary clone.

Advantage
  • Performance, we could reduce 1 time unnecessary clone cost.
Drawbacks
  • This requires changing the loop block to a .for_each() or introducing a .unwrap() call, even though it will never panic.
  • This requires the loop range has .len() method.
Example
fn set_something<T: Clone>(value: T) {
    for prop in props.iter() {
        prop.set(value.clone());
    }
}

This function will clone value props.len() times.

If we change the implementation to use zip + repeat_n, we could reduce it to clone value props.len() - 1 times.

fn set_something<T: Clone>(value: T) {
    props
        .iter()
        .zip(std::iter::repeat_n(value, props.len()))
        .for_each(|prop, value| prop.set(value));
}

Or

fn set_something<T: Clone>(value: T) {
    let mut value = std::iter::repeat_n(value, props.len());
    for prop in props.iter() {
        prop.set(value.next().unwrap());
    }
}
Comparison with existing lints

No response

Additional Context

No response

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

The issue names no repository files, tests, or lint entry point. Start by reviewing the proposed loop + clone and zip + repeat_n examples and the existing-lint comparison, then determine the lint's scope and expected diagnostics. Done means the unnecessary clone pattern is identified and an appropriate suggestion is defined.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
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.