Sub topic 10
Writing Clone by hand
This chapter assumes you can read #[derive(...)] attributes and write impl Trait for Type blocks. It also assumes you know how moves differ from copies, and that you know what .clone() does on a String. The chapters on deriving and on the cost of cloning cover those points.
Most types should use #[derive(Clone)]. The derive is correct, short, and stays correct when you add fields. Writing Clone by hand makes sense only when the derived behavior is wrong for your type. This chapter covers those cases, how to write the impl, and the mistakes to avoid.
What the derive does
For a struct, #[derive(Clone)] generates an impl that calls .clone() on every field and builds a new struct from the results. For an enum, it matches on the variant and clones that variant's fields. For a generic type such as Wrapper<T>, it adds the bound T: Clone to the impl.
A manual impl replaces that generated code. The trait has one required method:
pub trait Clone: Sized {
fn clone(&self) -> Self;
fn clone_from(&mut self, source: &Self) { /* default provided */ }
}You must write clone. clone_from has a default body that calls clone and assigns the result. You can leave it alone for now.
The basic shape
The simplest manual impl does exactly what the derive would do. It is worth writing once so you can see the pattern.
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 copied by plain assignment. The String field needs an explicit .clone(), because assigning it would move it out of &self, which the borrow checker rejects.
If you add a field to Counter later and forget to update clone, the struct literal will not compile. The compiler tells you about the missing field. That safety net is lost if you write clone with struct update syntax or by mutating a copy. Prefer building the new value field by field.
Reasons to write Clone by hand
Four situations come up often.
- A field should not be duplicated as-is. Examples are a unique ID, a statistics counter, or a cache.
- The derive adds a bound you do not want. This happens with generic types that hold a pointer to
T. - The type holds a trait object.
Box<dyn Trait>has noCloneimplementation, so it needs a helper method. - The type is
Copyand you want the simplest possibleclone. This is mostly a matter of style.
The sections below take them in turn.
Resetting or changing fields
A clone does not have to be a field-for-field duplicate. Suppose each session counts its requests. A clone starts a new session for the same user, so it should start counting from zero.
#[derive(Debug)]
struct Session {
user: String,
requests: u32,
}
impl Clone for Session {
fn clone(&self) -> Self {
Session {
user: self.user.clone(),
requests: 0,
}
}
}
fn main() {
let a = Session { user: String::from("ada"), requests: 41 };
let b = a.clone();
println!("{:?}", a);
println!("{:?}", b);
}This prints Session { user: "ada", requests: 41 } and then Session { user: "ada", requests: 0 }.
Be careful with this pattern. Callers expect x.clone() to behave like x. If a clone differs from its source in ways that matter, document it on the type. If the difference is large, a named method such as fork() or new_session() is clearer than a surprising Clone.
Avoiding the derived T: Clone bound
This case surprises many people. Take a handle that wraps an Rc<T>:
#[derive(Clone)]
struct Shared<T> {
inner: std::rc::Rc<T>,
}The derive generates impl<T: Clone> Clone for Shared<T>. That bound is unnecessary, because cloning an Rc copies a pointer and never touches the T. With the derive, Shared<NotClone> cannot be cloned even though it could be.
A manual impl removes the bound:
use std::rc::Rc;
struct Shared<T> {
inner: Rc<T>,
}
impl<T> Clone for Shared<T> {
fn clone(&self) -> Self {
Shared {
inner: Rc::clone(&self.inner),
}
}
}
struct NoClone(u8);
fn main() {
let a = Shared { inner: Rc::new(NoClone(7)) };
let b = a.clone();
println!("{} {}", Rc::strong_count(&a.inner), b.inner.0);
}This prints 2 7. NoClone does not implement Clone, yet Shared<NoClone> does. The standard library's own Rc<T> and Arc<T> are written this way.
Write Rc::clone(&self.inner) instead of self.inner.clone(). Both work, but the first shows that you are only bumping a reference count.
Cloning trait objects
A Box<dyn Shape> cannot call Clone::clone. Clone requires Self: Sized, and a trait object is unsized. So #[derive(Clone)] on a struct holding Vec<Box<dyn Shape>> fails.
The usual fix is a method on the trait that returns a new box, plus a manual Clone impl for the box type:
trait Shape {
fn area(&self) -> f64;
fn clone_box(&self) -> Box<dyn Shape>;
}
#[derive(Clone)]
struct Circle {
r: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.r * self.r
}
fn clone_box(&self) -> Box<dyn Shape> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn Shape> {
fn clone(&self) -> Self {
self.clone_box()
}
}
#[derive(Clone)]
struct Scene {
shapes: Vec<Box<dyn Shape>>,
}
fn main() {
let a = Scene { shapes: vec![Box::new(Circle { r: 2.0 })] };
let b = a.clone();
println!("{:.2} {:.2}", a.shapes[0].area(), b.shapes[0].area());
}This prints 12.56 12.56. The impl for Box<dyn Shape> is allowed because Shape is a local trait. It does not conflict with the standard impl<T: Clone> Clone for Box<T>, because dyn Shape is unsized and cannot satisfy that impl's implicit T: Sized. Each concrete type implements clone_box once, usually with the one-line body shown above. With the manual impl in place, Scene can use the derive again.
Manual Clone on a Copy type
Copy has Clone as a supertrait, so every Copy type must also be Clone. If you implement Copy yourself, the Clone body should return *self:
#[derive(Debug, Copy)]
struct Meters(f64);
impl Clone for Meters {
fn clone(&self) -> Self {
*self
}
}
fn main() {
let a = Meters(2.5);
let b = a.clone();
println!("{:?} {:?}", a, b);
}This works because Meters is Copy, so *self duplicates it without moving out of the reference. In practice, write #[derive(Clone, Copy)] and let the compiler do it. A hand-written Clone on a Copy type is flagged by the Clippy lint expl_impl_clone_on_copy when it does anything other than the derive would, because the two can then disagree. Generic code may use either Copy or Clone, and it expects them to give the same result.
The contract you are signing
The compiler checks only the signature of clone. It cannot check what the method means. Follow these rules so that code written against Clone stays correct:
- Equivalent result.
x.clone()should be usable whereverxwas, andx.clone() == xshould hold if the type implementsPartialEq. Deliberate exceptions, like the session counter above, belong in the type's documentation. - No side effects. Cloning should not print, write files, or change global state. Container code may clone at times you do not control.
- No panics in normal use.
Clone::clonecannot report an error. If duplication can fail, as it can for an operating system file handle, do not implementClone. Provide a method that returnsResult, asFile::try_clonedoes. - Independence. After cloning, mutating one value should not change the other, unless the type is documented as shared, like
Rc. AClonethat quietly aliases mutable state is a bug. - Cost is visible. If cloning is expensive, say so in the docs. Callers cannot see the cost at the
.clone()call site.
Overriding clone_from
The default clone_from(&mut self, source: &Self) builds a fresh value with source.clone() and drops the old one. A type that owns a buffer can often do better by copying into its existing allocation. You can override clone_from the same way you wrote clone. This is optional. The next chapters on clone_from cover when it pays off. If you never override it, your type still works.
Choosing between derive and manual
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Calling `self.clone()` inside `clone` | Infinite recursion and a stack overflow | Clone each field, not `self` |
| Forgetting `.clone()` on a `String` field | Error: cannot move out of `self.label` which is behind a shared reference | Add `.clone()` |
| Hand-writing `Clone` for a `Copy` type with different logic | `Copy` and `Clone` disagree, and Clippy warns | Use `#[derive(Clone, Copy)]` |
| Using `#[derive(Clone)]` on a pointer wrapper | Needless `T: Clone` bound | Write the impl without the bound |
| Writing `Clone` for a type owning a raw handle | Double release of the resource | Use `try_clone` style methods or `Rc` |
Summary
Prefer the derive. Write Clone by hand when a field needs different treatment, when the derived bound is too strict, or when a trait object is involved. Build the new value field by field so the compiler flags missing fields. Keep the result equivalent to the source, with no side effects, and document any difference.
Exercise
A struct Registry<T> holds items: Rc<Vec<T>>. You derive Clone for it and then find that Registry<Connection> cannot be cloned because Connection does not implement Clone. Write a manual Clone impl for Registry<T> that fixes this, and explain why the fix is sound.
Show answer
Write impl<T> Clone for Registry<T> { fn clone(&self) -> Self { Registry { items: Rc::clone(&self.items) } } }. The derive adds the bound T: Clone to the impl, but cloning an Rc only copies a pointer and increments the reference count. It never calls T::clone, so the bound is unnecessary. The manual impl has no bound on T, so Registry<Connection> can be cloned. All clones share the same underlying vector.