Sub topic 13
Pitfalls and Clippy lints around cloning
This chapter assumes you know ownership and borrowing, how Clone and Copy differ, and how to read compiler errors and run cargo clippy. It covers the mistakes that appear most often when people write .clone() and the lints that catch them.
Cloning to silence the borrow checker
The most common pitfall is adding .clone() until the compiler stops complaining. The program compiles, but you may have copied data you only needed to read.
fn shout(s: &str) -> String {
s.to_uppercase()
}
fn main() {
let name = String::from("ada");
// Wasteful: the clone is allocated and then thrown away.
let loud = shout(&name.clone());
println!("{loud} {name}");
}shout takes &str, so &name is enough. Clippy reports this as redundant_clone (in the nursery group, so it is off by default) or clone_on_copy and unnecessary_to_owned for related cases. Before you add a clone, ask whether a reference works.
Calling clone on a Copy type
Calling .clone() on a Copy type does the same work as plain assignment but adds noise. It also hides the fact that the type is cheap to duplicate.
fn main() {
let n: i32 = 42;
let m = n.clone(); // Clippy: clone_on_copy
let k = n; // preferred
println!("{m} {k}");
}Clippy's clone_on_copy lint is on by default and suggests removing the call.
Cloning a reference instead of the value
Method resolution can surprise you. If T does not implement Clone, then .clone() on a &T clones the reference, not the value. You get another &T.
struct Token(u32); // no Clone
fn main() {
let t = Token(7);
let r = &t;
let r2 = r.clone(); // copies the reference, type is &Token
println!("{}", r2.0);
}This compiles quietly. If you expected a Token, you will see a type error later, far from the cause. Clippy's clone_double_ref and the noop_method_call lint in rustc flag the cases that do nothing.
Cloning `Rc` and `Arc` with method syntax
rc.clone() and Rc::clone(&rc) do the same thing: they increment a counter. Readers, however, cannot tell from rc.clone() whether the call is cheap or a deep copy. Many teams write Rc::clone(&rc) to make sharing visible. Clippy's optional clone_on_ref_ptr lint (in the restriction group) enforces this style.
use std::rc::Rc;
fn main() {
let a = Rc::new(String::from("shared"));
let b = Rc::clone(&a); // clearly a pointer copy
println!("{} {}", Rc::strong_count(&a), b);
}Cloning inside loops
A clone inside a hot loop multiplies its cost by the number of iterations. Hoist it out, or borrow.
fn count_matches(words: &[String], needle: &str) -> usize {
words.iter().filter(|w| w.as_str() == needle).count()
}
fn main() {
let words = vec![String::from("a"), String::from("b"), String::from("a")];
println!("{}", count_matches(&words, "a"));
}Iterating with .iter() and comparing through references avoids cloning every String. The same applies to .iter().cloned().collect::<Vec<_>>() just to read the result once.
Clone does not mean independent
A clone is only independent if every field is deeply cloned. Types with Rc<RefCell<T>> fields clone the pointer, so both copies see each other's changes.
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Clone)]
struct Shared {
data: Rc<RefCell<Vec<i32>>>,
}
fn main() {
let a = Shared { data: Rc::new(RefCell::new(vec![1])) };
let b = a.clone();
b.data.borrow_mut().push(2);
println!("{:?}", a.data.borrow()); // [1, 2]
}The derive is correct here, but the result may not be what a reader expects. Document it, or write Clone by hand if you want a deep copy.
Quick reference
| Lint | Default | What it flags |
|---|---|---|
| `clone_on_copy` | warn | `.clone()` on a `Copy` type |
| `redundant_clone` | allow (nursery) | A clone whose source is never used again |
| `clone_on_ref_ptr` | allow (restriction) | `.clone()` on `Rc` or `Arc` |
| `assigning_clones` | allow (pedantic) | `a = b.clone()` where `a.clone_from(&b)` can reuse memory |
Exercise
In the code let r2 = r.clone(); where r: &Token and Token does not implement Clone, what is the type of r2, and why?
Show answer
r2 is &Token. Because Token is not Clone, method resolution finds Clone for &T (references are Copy), so it copies the reference and does not duplicate the Token.
Exercise
A function takes name: String but only prints it. Callers write greet(user.name.clone()). How do you remove the clone?
Show answer
Change the parameter to &str (or &String) and call greet(&user.name). The function only reads the value, so no ownership or copy is needed.