Sub topic 13
Pitfalls and Clippy lints around cloning
This chapter assumes you know how Copy and Clone differ, how to derive them, and what a clone costs for String, Vec, Rc and Arc. It covers the mistakes that appear most often in real code, and the Clippy lints that catch many of them.
Pitfall 1: cloning to silence the borrow checker
The most common misuse of .clone() is making a compiler error go away without understanding it. A function that only reads its argument should borrow it. If it takes ownership, callers must clone to keep using their data.
fn print_all(names: Vec<String>) {
for name in &names {
println!("{name}");
}
}
fn main() {
let names = vec![String::from("Ada"), String::from("Grace")];
print_all(names.clone()); // allocates a new Vec and two new Strings
println!("{}", names.len());
}This compiles and runs, but it copies every string just so the function can read them. Take a slice instead:
fn print_all(names: &[String]) {
for name in names {
println!("{name}");
}
}
fn main() {
let names = vec![String::from("Ada"), String::from("Grace")];
print_all(&names);
println!("{}", names.len());
}Before you add a .clone(), ask whether the callee really needs ownership. If it does not, change the signature. If it does, the clone is the honest cost of that design.
Pitfall 2: cloning a reference instead of the value
Method resolution looks for clone on the receiver type first, then on references to it. If T does not implement Clone, then r.clone() on a &T finds Clone for &T and copies the reference. The code compiles, and you get no new T.
struct Token; // does not implement Clone
fn main() {
let t = Token;
let r = &t;
let r2 = r.clone(); // clones the &Token, not the Token
let _ = (r, r2);
}Recent compilers warn here with the noop_method_call lint. The problem is worse in generic code. In fn f<T>(x: &T) { let y = x.clone(); } with no T: Clone bound, y is a &T, not a T. The error shows up later as a type mismatch far from the cause. Add the T: Clone bound if you want a value.
Pitfall 3: derive adds bounds you may not want
#[derive(Clone)] on a generic type adds T: Clone for every type parameter, even when no field needs it. A handle that only holds an Rc<T> is always cheap to clone, but the derived impl refuses when T is not Clone. The fix is to implement Clone by hand with no bound on T.
use std::rc::Rc;
struct Handle<T> {
inner: Rc<T>,
}
impl<T> Clone for Handle<T> {
fn clone(&self) -> Self {
Handle {
inner: Rc::clone(&self.inner),
}
}
}
struct Opaque; // not Clone
fn main() {
let a = Handle { inner: Rc::new(Opaque) };
let b = a.clone();
println!("{}", Rc::strong_count(&a.inner));
drop(b);
}This prints 2. With #[derive(Clone)] on Handle<T>, the call a.clone() fails with an error saying the method exists but its trait bounds were not satisfied. The same bound rule applies to Copy.
Pitfall 4: silent copies of mutable data
A Copy type never moves, so a mutation can land on a copy you did not intend. Reading points[0] into a let binding copies the element. Changes to the binding do not reach the vector.
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let mut points = vec![Point { x: 0, y: 0 }, Point { x: 1, y: 1 }];
let mut first = points[0]; // copy
first.x = 99;
println!("{:?}", points[0]); // Point { x: 0, y: 0 }
points[0].x = 99; // mutate in place
println!("{:?}", points[0]); // Point { x: 99, y: 0 }
}With a non-Copy type, the first line would be a move error, which exposes the mistake. Copy removes that safety signal. When you want to change the original, borrow it: let first = &mut points[0];, or use iter_mut() in loops.
Other consequences of Copy:
- Adding
Copyto a type later is compatible. Removing it breaks every caller that relied on implicit copies. - A
Copytype that is large, such as a struct holding a[u8; 4096], is copied bymemcpyon every pass by value. Clippy's pedanticlarge_types_passed_by_valuelint flags this. Pass such types by reference.
Pitfall 5: shared handles that clone "shallowly"
Cloning an Rc<RefCell<T>> or Arc<Mutex<T>> produces another handle to the same data. A mutation through one handle is visible through the other. Cloning the RefCell<T> itself, or a plain struct containing one, produces independent data. Mixing these up gives either surprising sharing or surprising independence.
| Value being cloned | Result | Mutation visible through the original? |
|---|---|---|
| `Rc<RefCell<Vec<i32>>>` | New handle, same vector | Yes |
| `RefCell<Vec<i32>>` | New cell with a copied vector | No |
| `Arc<Mutex<Counter>>` | New handle, same counter | Yes |
| `Vec<Rc<T>>` | New vector, same `T` values | Yes, for the `T` values |
When you review code, check which layer clone stops at. Writing Rc::clone(&a) instead of a.clone() makes it clear that you are copying a pointer.
Clippy lints for cloning
Run Clippy with cargo clippy. The lints below relate to cloning. Their default levels differ, so a clean default run does not mean they all passed.
| Lint | Group | What it flags | Column | Column |
|---|---|---|---|---|
| `clone_on_copy` | complexity (warn) | `.clone()` on a `Copy` type, where a plain copy works | ||
| `map_clone` | style (warn) | `.map(\ | x\ | x.clone())` that should be `.cloned()` or `.copied()` |
| `non_canonical_clone_impl` | suspicious (warn) | A manual `Clone` on a `Copy` type that does more than `*self` | ||
| `unnecessary_to_owned` | perf (warn) | Allocating with `to_owned` or `to_string` when a borrow would do | ||
| `redundant_clone` | nursery (off) | A clone whose original is never used afterward | ||
| `assigning_clones` | pedantic (off) | `a = b.clone()` that could be `a.clone_from(&b)` | ||
| `implicit_clone` | pedantic (off) | `to_owned` or `to_vec` on a value that is already owned | ||
| `expl_impl_clone_on_copy` | pedantic (off) | A hand-written `Clone` on a type that is `Copy` | ||
| `clone_on_ref_ptr` | restriction (off) | `.clone()` on `Rc` or `Arc` instead of `Rc::clone(&x)` |
The group names and defaults reflect recent Clippy releases and sometimes change. Check cargo clippy --help or the Clippy lint list for your toolchain.
Here are the two most common warnings and their fixes:
fn main() {
let n: u32 = 5;
let m = n.clone(); // clippy::clone_on_copy
let m2 = n; // preferred
let names = vec![String::from("a"), String::from("b")];
let v1: Vec<String> = names.iter().map(|s| s.clone()).collect(); // clippy::map_clone
let v2: Vec<String> = names.iter().cloned().collect(); // preferred
println!("{m} {m2} {} {}", v1.len(), v2.len());
}You can turn on the opt-in lints for a whole package in Cargo.toml (this needs Cargo 1.74 or later):
[lints.clippy]
clone_on_ref_ptr = "warn"
assigning_clones = "warn"A review checklist
When a pull request adds .clone(), work through these questions:
- Could the function take a reference or slice instead of an owned value?
- Is the receiver a reference to a type without
Clone, so the call copies only the pointer? - Is the type
Copy? If so, remove the call. - Is the clone of an
RcorArc? If so, writeRc::clone(&x)so readers see it is cheap. - Is the clone inside a loop? If so, check whether it can move outside the loop.
- If you are overwriting an existing value, would
clone_fromreuse its allocation?
Exercise
A generic type Cache<T> { data: Rc<Vec<T>> } uses #[derive(Clone)]. Calling .clone() on a Cache<Opaque> fails to compile, where Opaque does not implement Clone. Why does it fail, and how do you fix it?
Show answer
The derive adds a T: Clone bound to the generated impl, even though cloning an Rc never needs T: Clone. Remove the derive and write impl<T> Clone for Cache<T> { fn clone(&self) -> Self { Cache { data: Rc::clone(&self.data) } } }, which has no bound on T.
Exercise
Clippy warns clone_on_copy on let b = a.clone(); where a: Point and Point derives Copy. What should the line be, and why is .clone() harmful beyond style?
Show answer
Write let b = a;. The call adds noise, and it hides whether the type is Copy. If the type later stops being Copy, the stray .clone() quietly turns an implicit copy into an explicit, possibly costly clone.