Sub topic 7
Which standard library types are Copy or Clone
This chapter surveys which standard library types implement Copy and Clone, and the rules that decide it. It assumes you know the basics of structs, enums and traits, and that you can read ownership errors such as "borrow of moved value". It also assumes you have seen #[derive(Clone, Copy)]. The chapter builds a mental map you can use without checking the docs every time.
The rule behind the map
Almost every standard library type follows one of three patterns.
- Plain data that fits in a fixed number of bytes with no ownership of anything else is
Copy, and therefore alsoClone. - A type that owns heap memory or another resource is
Cloneonly when duplicating that resource makes sense. It is neverCopy. - A type that wraps other types is
CopyorCloneonly when its contents are. The standard library writes this as a conditional implementation, such asimpl<T: Clone> Clone for Vec<T>.
Copy requires Clone. Every Copy type is also Clone, and for those types .clone() does the same thing as an assignment.
Mermaid is not allowed to be empty, so here is the actual decision flow as a diagram:
Types that are Copy
These are the types you can assign, pass and return many times without a move.
- Integers, floats,
boolandchar. - The unit type
()and the never type!. - Shared references
&T, for anyT, including&strand&[T]. - Raw pointers
*const Tand*mut T. - Function pointers such as
fn(i32) -> i32, and function items. - Tuples, up to length 12, when every element is
Copy. - Arrays
[T; N]whenTisCopy. Option<T>whenTisCopy, andResult<T, E>when bothTandEareCopy.- Small value types:
Duration,Instant,SystemTime,Ordering,Ipv4Addr,IpAddr,SocketAddr,TypeId,PhantomData<T>, theNonZerointeger types, andWrapping<T>andReverse<T>whenTisCopy. - Closures, when everything they capture is
Copy(shared references count). A closure that captures aStringby move is notCopy.
The compiler can check any claim like this for you. A function with a trait bound and an empty body is a cheap assertion.
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;
fn assert_copy<T: Copy>() {}
fn assert_clone<T: Clone>() {}
fn main() {
assert_copy::<i32>();
assert_copy::<&str>();
assert_copy::<(u8, char)>();
assert_copy::<[f64; 3]>();
assert_copy::<Option<u32>>();
assert_copy::<Duration>();
assert_copy::<fn(i32) -> i32>();
assert_copy::<*const u8>();
assert_clone::<String>();
assert_clone::<Vec<String>>();
assert_clone::<Box<i32>>();
assert_clone::<Rc<RefCell<i32>>>();
println!("all bounds hold");
}If you change any line to a type that does not qualify, such as assert_copy::<String>(), the program stops compiling. The error names the unmet bound.
Types that are Clone but not Copy
Any type that owns heap memory falls here. Cloning gives you a new, independent owner.
| Type | Clone condition | What `.clone()` does |
|---|---|---|
| `String` | Always | Allocates a new buffer and copies the bytes |
| `Vec<T>` | `T: Clone` | Allocates a new buffer and clones each element |
| `Box<T>` | `T: Clone` | Allocates a new box and clones the contents |
| `HashMap<K, V, S>` | `K: Clone`, `V: Clone`, `S: Clone` | Clones the table, every key and every value |
| `BTreeMap<K, V>`, `HashSet<T>`, `VecDeque<T>` | Contents are `Clone` | Clones the whole collection |
| `Option<T>` | `T: Clone` | Clones the contained value if present |
| `Rc<T>`, `Arc<T>` | Always, even if `T` is not `Clone` | Increments a reference count and copies the pointer |
| `Cow<'a, B>` | Always | Copies the borrow, or clones the owned value |
| `RefCell<T>` | `T: Clone` | Clones the contents; panics if the cell is mutably borrowed |
| `Cell<T>` | `T: Copy` | Copies the value into a new, independent cell |
The collections follow the "clone is as deep as the contents" rule. Cloning a Vec<String> allocates once for the vector and once for every string.
The Rc and Arc exception
Rc<T> and Arc<T> do not clone the T. They share it. For that reason they implement Clone without requiring T: Clone, which lets you share a value whose type has no Clone implementation.
use std::rc::Rc;
struct Config {
name: String,
}
fn main() {
let a = Rc::new(Config { name: String::from("prod") });
let b = Rc::clone(&a);
println!("{} {}", a.name, Rc::strong_count(&b));
}This prints prod 2. Config does not implement Clone, but Rc<Config> does.
Many teams write Rc::clone(&a) instead of a.clone(). Both do the same thing. The first form tells a reader that this is a cheap pointer copy and not a deep copy.
Cell is Clone but not Copy
Cell<T> is a good example of why Copy and Clone are separate. A Cell<i32> can be cloned, because copying its value out is safe. It is not Copy, because an implicit duplicate of a mutable cell would be surprising.
use std::cell::Cell;
fn main() {
let c = Cell::new(1);
let d = c.clone();
d.set(5);
println!("{} {}", c.get(), d.get());
}This prints 1 5. The clone is independent of the original.
Types that are neither
Some types cannot be duplicated by copying their bytes or by any general rule, so the standard library gives them no Clone implementation.
&mut T. A second copy would break the rule that only one mutable reference exists.Mutex<T>andRwLock<T>. They guard shared state, and cloning one would produce a second lock that guards nothing in common with the first.File,TcpStreamand other handles to operating system resources.Fileoffers a fallibletry_clonemethod instead, because duplicating a handle can fail.- The atomic types, such as
AtomicUsize. JoinHandle<T>. You can join a thread only once.- Trait objects such as
Box<dyn Trait>, unless you add your own cloning method.
You cannot derive Clone for a struct that contains any of these, unless the field is wrapped in something shareable such as Arc<Mutex<T>>.
Gotcha: calling clone on a reference
.clone() uses method resolution. If the type behind a reference does not implement Clone, the call resolves to Clone for &T, and you silently get a copy of the reference, not of the value.
struct Token;
fn main() {
let t = Token;
let r = &t;
let r2 = r.clone();
println!("{}", std::ptr::eq(r, r2));
}This prints true. Token has no Clone implementation, so r.clone() copies the reference. Both variables point at the same value. The compiler warns that the call does nothing.
The surprise appears when you add #[derive(Clone)] to a generic struct and forget that the derive adds a T: Clone bound. A clone of Wrapper<&Token> works, but a clone of Wrapper<Token> does not. When you see an error about a missing Clone bound on a type you thought was clonable, look at the type parameters first.
Derived implementations are conditional
When you derive Clone or Copy on a generic type, the derive adds the bound to every type parameter, even if a parameter appears only inside an Rc or a PhantomData. The standard library's own types are written by hand to avoid this. That is why Rc<T> and PhantomData<T> do not need T: Clone or T: Copy, while a struct you derive does:
use std::marker::PhantomData;
#[derive(Clone, Copy)]
struct Id<T> {
raw: u32,
_kind: PhantomData<T>,
}
struct User;
fn main() {
let a: Id<User> = Id { raw: 7, _kind: PhantomData };
// The derive requires `User: Clone` and `User: Copy` here, so
// the next line would not compile with a plain derive:
// let b = a;
// println!("{}", a.raw);
println!("{}", a.raw);
}Here Id<User> is not Copy, because User is not Copy, even though the struct holds only a u32 and a zero-sized marker. If you want Id<T> to be Copy for every T, write the two impl blocks yourself with no bound on T. Later chapters on writing Clone by hand cover the syntax.
A practical checklist
When you are unsure about a standard library type:
- Ask whether it is plain fixed-size data. If so, it is probably
Copy. - Ask whether it owns heap memory. If so, it is
Cloneand neverCopy. - Ask whether it is a shared pointer. If so,
.clone()is cheap and does not need the contents to beClone. - Ask whether it guards a resource or a lock. If so, it is probably neither.
- If you are still unsure, write an
assert_copy::<T>()call and let the compiler answer.
Exercises
Exercise
For each type, say whether it is Copy, Clone only, or neither: (i32, bool), Vec<u8>, &mut i32, Option<String>, Mutex<i32>, &String.
Show answer
(i32, bool) is Copy, because every element is Copy. Vec<u8> is Clone only, because it owns a heap buffer. &mut i32 is neither, because a second mutable reference would break exclusivity. Option<String> is Clone only, because String is Clone but not Copy. Mutex<i32> is neither, because it guards shared state and has no Clone implementation. &String is Copy, because every shared reference is Copy.
Exercise
A struct Job has no Clone implementation. Does Rc<Job> implement Clone, and does Vec<Job> implement Clone? Explain what .clone() on an Rc<Job> does.
Show answer
Rc<Job> implements Clone, because Rc<T> is Clone for every T. Vec<Job> does not, because Vec<T> is Clone only when T: Clone. Calling .clone() on an Rc<Job> increments the reference count and copies the pointer. It does not duplicate the Job, so both handles see the same value.