rust-lang / rust-lang/rust-clippy

Add lint to detect unnecessary `clone()` for `AsRef`-taking function

Open
#12,455 0 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

Consider this code:

use std::path::*;

fn item(_x: impl AsRef<Path>) {}

pub fn work(x: PathBuf) {
    item(x.clone()); // unnecessary clone
    item(&x);
}

This should be better written as

use std::path::*;

fn item(_x: impl AsRef<Path>) {}

pub fn work(x: PathBuf) {
    item(&x);
    item(&x);
}

Clippy as a bunch of lints against unnecessary borrowing, which is syntactic noise but ultimately usually harmless. Unnecessary cloning however can make the program slower for no good reason, so it is IMO quite relevant to lint against as well.

Clippy is already able to detect similar cases, like unnecessary to_owned():

use std::path::*;

fn item(_x: impl AsRef<Path>) {}

pub fn work(x: &Path) {
    item(x.to_owned()); // clippy lints here
    item(x);
}
Advantage

Same as the existing unnecessary_to_owned: avoids unnecessary copies and function calls, making the code both less noisy and faster.

Drawbacks

If it can be implemented without false positivies, I cannot think of any drawbacks.

Example

(see description above)

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 by locating the existing unnecessary_to_owned lint, since the issue identifies it as a similar case. Compare its implementation and tests with the proposed clone() pattern, then define coverage and false-positive cases for functions taking AsRef; done means the examples are linted without incorrect suggestions and the relevant tests pass.

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
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.