rust-lang / rust-lang/rust-clippy
Avoid an AsRef-motivated unnecessary clone
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
Although a perk of "AsRef" is that it enables callers to provide either T or &T as input to a function, the resolution to a non-reference type seems suboptimal if a caller clones the input argument to make this invocation possible.
A linter could identify if a calling function clones an object to provide it as an argument to an "AsRef" method - very similarly to the existing "redundant clone" lint.
Categories (optional)
- Kind: Seems like possibly perf, or style?
What is the advantage of the recommended code over the original code
- Avoids unnecessary clone.
- Instructs callers on the different usages of AsRef, a known "tricky area" for Rust newbies.
Drawbacks
None... that I know of?
Example
fn is_hello<T: AsRef<str>>(s: T) {
assert_eq!("hello", s.as_ref());
}
let s = "hello".to_string();
is_hello(s.clone());
is_hello(s);
Could be written as:
fn is_hello<T: AsRef<str>>(s: T) {
assert_eq!("hello", s.as_ref());
}
let s = "hello".to_string();
is_hello(&s);
is_hello(s);
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 by examining the existing "redundant clone" lint and compare its behavior with the AsRef example in this issue. Define how calls that clone an argument for an AsRef method should be detected, what recommendation should be shown, and add coverage demonstrating both the cloned and borrowed forms.
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