Sub topic 10
Writing Clone by hand
This chapter assumes you know how to derive Clone and Copy, how moves work, and how to read compiler errors. Here you will implement Clone yourself and learn when that is worth doing.
Why not just derive?
#[derive(Clone)] calls .clone() on every field in order. That is correct for most types. You write the trait by hand when you want something different:
- A field should not be copied, such as a cache that can be rebuilt.
- A field should be reset, such as a counter that starts at zero in the copy.
- The type holds a resource that needs special handling, such as a raw pointer or a unique ID.
- The derive adds a bound you do not want (see the pitfalls below).
The shape of a manual implementation
Clone has one required method, clone. It takes &self and returns a new Self.
struct Counter {
hits: u32,
label: String,
}
impl Clone for Counter {
fn clone(&self) -> Self {
Counter {
hits: self.hits,
label: self.label.clone(),
}
}
}
fn main() {
let a = Counter { hits: 3, label: String::from("home") };
let b = a.clone();
println!("{} {}", b.hits, b.label);
}The u32 field is Copy, so self.hits copies it. The String field is not Copy, and you cannot move it out of &self. So you call self.label.clone() to get an owned duplicate. This matches what the derive would produce, so here the manual version adds nothing. It is the starting point for the changes below.
Customizing the copy
Suppose the counter should start fresh in each clone, while keeping the label.
struct Counter {
hits: u32,
label: String,
}
impl Clone for Counter {
fn clone(&self) -> Self {
Counter {
hits: 0,
label: self.label.clone(),
}
}
}
fn main() {
let a = Counter { hits: 3, label: String::from("home") };
let b = a.clone();
println!("{} {}", a.hits, b.hits);
}This prints 3 0. The clone is a new value that is related to the original but not equal to it. Be careful with this. Code that calls .clone() usually expects an equivalent value. Surprising behavior should be rare and documented.
Skipping a field
A cache is a common case. Suppose you store a computed value that is cheap to rebuild.
struct Document {
text: String,
word_count_cache: Option<usize>,
}
impl Clone for Document {
fn clone(&self) -> Self {
Document {
text: self.text.clone(),
word_count_cache: None,
}
}
}
impl Document {
fn word_count(&mut self) -> usize {
if let Some(n) = self.word_count_cache {
return n;
}
let n = self.text.split_whitespace().count();
self.word_count_cache = Some(n);
n
}
}
fn main() {
let mut a = Document {
text: String::from("one two three"),
word_count_cache: None,
};
println!("{}", a.word_count());
let mut b = a.clone();
println!("{}", b.word_count());
}The clone starts with an empty cache and fills it on first use. Both calls print 3.
Pitfalls
- Forgetting a field. Struct literal syntax forces you to name every field, so the compiler catches this. Avoid
..Default::default()inclonebecause it hides omissions. - Calling
self.clone()insideclone. This recurses forever. Clone the fields, notself. - Derive bounds on generics. For
struct Wrapper<T>(Rc<T>), the derive requiresT: Clone, even though cloning anRcnever clones theT. A manualimpl<T> Clone for Wrapper<T>with no bound onTis more accurate. - Breaking
Copy. If a type is alsoCopy, itsCloneshould behave like a plain copy. The standard library documents this expectation, and generic code relies on it.
Exercise
A struct has a name: String field and an id: u64 field. You want every clone to keep the name but get id set to 0. Write the Clone implementation.
Show answer
impl Clone for Item { fn clone(&self) -> Self { Item { name: self.name.clone(), id: 0 } } } The String needs an explicit .clone() because it cannot be moved out of &self. The u64 is replaced with a constant.
Exercise
Why does struct Wrapper<T>(Rc<T>) benefit from a hand-written Clone instead of a derived one?
Show answer
The derive adds a T: Clone bound to the impl. Cloning an Rc<T> only copies the pointer and bumps the count, so T does not need to be Clone. A manual impl<T> Clone for Wrapper<T> { fn clone(&self) -> Self { Wrapper(Rc::clone(&self.0)) } } removes the unneeded bound.