Sub topic 4
Copy versus Clone side by side
This chapter assumes you know basic Rust syntax (structs, enums, functions, traits) and the ownership and borrowing basics. You should also be comfortable reading compiler error messages. The previous chapters covered moves, Copy, and Clone one at a time. Here we put them next to each other and focus on the differences that matter in daily code.
The short version
Copy and Clone are both traits that describe duplicating a value. They differ in who decides when the duplication happens and what it may cost.
Copyis a marker trait. It has no methods. If a type implements it, the compiler duplicates the value silently whenever you assign it, pass it to a function, or return it. The duplication is always a plain bitwise copy of the bytes.Cloneis an ordinary trait with aclonemethod. Duplication happens only when you write.clone(). The method can run arbitrary code, so it may allocate memory, copy a large buffer, or just bump a counter.
Clone is a supertrait of Copy. The declaration is trait Copy: Clone. Any type that is Copy must also be Clone, but most Clone types are not Copy.
| Property | `Copy` | `Clone` |
|---|---|---|
| Has methods | No, marker trait | Yes, `clone` and `clone_from` |
| When it happens | Implicitly, on every use by value | Explicitly, when you call `.clone()` |
| What it does | Bitwise copy of the bytes | Any code you write or derive |
| Cost | Always cheap, proportional to the size of the value | Anything from free to very expensive |
| Can you customize it | No | Yes, by implementing `clone` by hand |
| Supertrait | `Clone` | None |
| Original usable after assignment | Yes | Yes, if you cloned. No, if you moved |
Seeing the difference in code
The first example uses a type that is Copy and a type that is not.
fn main() {
let a = 5;
let b = a;
println!("{a} {b}");
let s = String::from("hi");
let t = s;
// println!("{s}"); // error: borrow of moved value: `s`
println!("{t}");
}An i32 is Copy, so let b = a; leaves a valid. A String is not Copy, so let t = s; moves the value and s can no longer be used. If you want two independent strings, you have to ask for it:
fn main() {
let s = String::from("hi");
let t = s.clone();
println!("{s} {t}");
}Both bindings are usable because clone built a second String with its own heap buffer.
The key point is that the source code of a Copy type looks identical to the source code of a move. Nothing at the call site tells you whether let b = a; copies or moves. The type decides. When you read unfamiliar code, you need to know whether the types involved are Copy.
What a bitwise copy means
When a type is Copy, the compiler copies its bytes from one location to another, just as memcpy would. This is safe only when those bytes fully describe the value and nobody has to clean anything up.
Consider a String. Its bytes are a pointer, a length, and a capacity. If the compiler copied those bytes, you would have two String values pointing at the same heap buffer. Both would try to free it when dropped, which is a double free. Rust prevents this by making String non-Copy, so assignment moves ownership instead.
Clone for String does something different. It allocates a new buffer, copies the text into it, and returns a new String that owns the new buffer. The two values are independent.
Copy is a promise about the type
Because Copy types are duplicated without any visible call, implementing Copy is a strong promise: the type is cheap to duplicate and has no ownership of external resources. Once you publish a type as Copy, callers will rely on it. Removing Copy later breaks any code that used the value after passing it somewhere.
Clone makes a weaker promise. It says only that a duplicate can be produced on request.
The Copy promise has a second consequence. A type that is Copy cannot implement Drop. The compiler rejects the combination, because a type with cleanup code cannot safely be duplicated by copying bytes.
Deriving both together
When all fields of a struct are Copy, you can derive both traits. You must derive Clone as well, since it is a supertrait.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
let q = p;
println!("{:?} {:?}", p, q);
}Here let q = p; copies. Both p and q remain usable. If one field were a String, the derive would fail:
// #[derive(Clone, Copy)] // error: the trait `Copy` cannot be implemented for this type
#[derive(Debug, Clone)]
struct User {
id: u32,
name: String,
}
fn main() {
let u = User { id: 1, name: String::from("Ada") };
let v = u.clone();
println!("{:?} {:?}", u, v);
}User is still Clone. Cloning it clones each field in turn, so name gets a fresh heap buffer. Moving a User still transfers ownership, as with any non-Copy type.
A third option: shared ownership
Some types are Clone but the clone is not a deep copy. Rc and Arc are the standard examples. Cloning them copies a pointer and increments a reference count. The data itself is not duplicated.
use std::rc::Rc;
fn main() {
let a = Rc::new(vec![1, 2, 3]);
let b = Rc::clone(&a);
println!("{}", Rc::strong_count(&a));
println!("{}", Rc::ptr_eq(&a, &b));
}This prints 2 and then true. Both a and b point to the same vector. So "clone" does not always mean "make an independent copy". For Rc it means "make another owner of the same data". This is why Rc cannot be Copy: it must run code on every duplication (the count update) and on every drop.
Writing Rc::clone(&a) instead of a.clone() is a common convention. It signals to the reader that the call is cheap and does not copy the contents.
Cost comparison
The cost difference is the main practical reason to keep the two traits apart.
| Type | Duplicated by | Cost |
|---|---|---|
| `i32`, `f64`, `bool`, `char` | Copy | A few bytes |
| `(i32, i32)`, `[u8; 16]` | Copy | Size of the value |
| `&T` | Copy | One pointer |
| `String` | Clone | Allocation plus copy of the text |
| `Vec<T>` | Clone | Allocation plus a clone of every element |
| `Rc<T>`, `Arc<T>` | Clone | Counter increment, atomic for `Arc` |
A large Copy type is still copied every time it is passed by value. An array such as [u8; 1_000_000] is Copy, and passing it to a function copies a megabyte. The compiler may optimize some copies away, but you should not count on it. For big values, pass a reference even when the type is Copy.
How the two interact in generic code
A generic function sees only the bounds you give it. Without a bound, a T can only be moved. Adding Clone lets you duplicate explicitly. Adding Copy lets you duplicate implicitly.
fn largest<T: PartialOrd + Copy>(items: &[T]) -> Option<T> {
let mut iter = items.iter().copied();
let mut max = iter.next()?;
for x in iter {
if x > max {
max = x;
}
}
Some(max)
}
fn main() {
println!("{:?}", largest(&[3, 9, 4]));
println!("{:?}", largest::<f64>(&[]));
}The Copy bound allows returning elements by value out of a borrowed slice. You cannot move out of a slice, so without Copy or Clone the function would not compile. Using Clone instead would widen the set of accepted types, so String would work too, but it would make the cost of each call less predictable. Choose the bound that matches what the function really needs. Because Copy implies Clone, a function bounded by Copy may also call .clone(), though that is redundant.
Edge cases worth knowing
- Moves of
Copytypes are copies. There is no way to move aCopyvalue in a way that invalidates the source. The original binding is always still usable. - Clone of a Copy type should match Copy. If you implement both by hand,
cloneshould return a value equal to a bitwise copy. A derivedCloneon aCopytype does this. Making them differ is legal but surprising. - Generic structs derive conditionally.
#[derive(Clone, Copy)] struct Pair<T>(T, T);producesimpl<T: Clone> Cloneandimpl<T: Copy> Copy. SoPair<i32>isCopybutPair<String>is onlyClone... and in factPair<String>is not evenCloneunlessString: Clone, which it is, so it isClone. - Mutable references are not
CopyorClone.&mut Tis exclusive, so duplicating it would allow aliasing. Shared references&Tare both. - Closures implement
CopyandClonewhen all captured values do.
Choosing between them
Use these questions in order when deciding how to duplicate a value or how to design a type.
- Is the type
Copy? Then just use it. If it is large, prefer a reference. - Do you only need to read the value? Borrow it with
&and skip duplication. - Do you need an independent owned value? Call
.clone()and accept the cost. - Do several parts of the program need to own the same data? Use
RcorArcand clone the handle.
Exercise
Given #[derive(Clone, Copy)] struct Id(u32); and #[derive(Clone)] struct Name(String);, which of these lines compile? (1) let a = Id(1); let b = a; println!("{}", a.0); (2) let n = Name(String::new()); let m = n; println!("{}", n.0); (3) let n = Name(String::new()); let m = n.clone(); println!("{}", n.0);
Show answer
Lines (1) and (3) compile. In (1), Id is Copy, so let b = a; copies and a stays valid. In (2), Name is not Copy, so let m = n; moves n and the later use of n.0 is an error. In (3), .clone() creates an independent Name, so n is still valid.
Exercise
Why can Rc<T> be Clone but not Copy, and what does Rc::clone actually duplicate?
Show answer
Rc::clone copies only the pointer and increments the reference count. The shared data is not duplicated. Rc cannot be Copy because duplicating it must run code (the count update), and a Copy duplication is only a bitwise copy of bytes. It also has cleanup code on drop, which a Copy type is not allowed to have.