rust-lang / rust-lang/rust-clippy
Remove `.copied()` or `.cloned()` when possible
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
Currently, cloned_instead_of_copied lint suggests to replace cloned() with copied() in these examples:
pub fn lengths(items: &[&str]) -> usize {
items.iter().cloned().map(|one| one.len() + 1).sum()
}
// both key and value are simple copiable enums
pub fn getter(key: Key, vals: &HashMap::<Key, Value>) {
if let Some(Value::X) = vals.get(&key).cloned() {
println!("Found X");
}
}
but Rust allows .cloned() to be fully removed. A lint should suggest that instead of suggesting copied. I am not certain if this should be an extension to cloned_instead_of_copied or if its a new lint.
Advantage
- Shorter, possibly faster code
Drawbacks
No response
Example 1
#[must_use]
pub fn lengths(items: &[&str]) -> usize {
items.iter().cloned().map(|one| one.len() + 1).sum()
}
fn main() {
println!("Sum={}", lengths(&["hello", "world"]));
}
Could be written as:
pub fn lengths(items: &[&str]) -> usize {
items.iter().map(|one| one.len() + 1).sum()
}
Example 2
use std::collections::HashMap;
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum Key{ A, B, C }
#[derive(Clone, Copy, Debug)]
pub enum Value{ X, Y, Z }
fn main() {
let vals = HashMap::<Key, Value>::new();
getter(Key::A, &vals);
}
pub fn getter(key: Key, vals: &HashMap::<Key, Value>) {
if let Some(Value::X) = vals.get(&key).cloned() {
println!("Found X");
}
}
Could be written as:
pub fn getter(key: Key, vals: &HashMap::<Key, Value>) {
if let Some(Value::X) = vals.get(&key) {
println!("Found X");
}
}
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 locating the cloned_instead_of_copied lint implementation and its tests, then compare how the two examples are handled. Done means the appropriate lint suggests removing .cloned() where the borrowed value can be matched or mapped directly, rather than suggesting .copied().
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
- 42/100