Sub topic 7
Which standard library types are Copy or Clone
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how to read compiler errors. It also assumes you know that Copy means implicit bitwise duplication and Clone means explicit duplication with .clone(). Here you will learn how to predict which standard library types have which trait, without memorizing a list.
The rule of thumb
A type is Copy when a plain bitwise copy produces a fully valid, independent value. That is only true when the value owns no heap memory and no resource that must be released exactly once. A type is Clone when the library authors found a sensible way to duplicate it.
Every Copy type is also Clone, because Copy requires Clone as a supertrait. The reverse is not true.
Copy types
These standard types are Copy:
- Integers (
i8toi128,u8tou128,isize,usize), floats (f32,f64),bool, andchar. - Shared references,
&T, for anyT. Copying a reference copies the pointer, not the data. - Raw pointers, function pointers, and the never type.
Option<T>, whenTisCopy.- Tuples, arrays
[T; N], and closures whose captures are allCopy, when every element isCopy. - Small value types such as
std::cmp::Orderingandstd::time::Duration.
Notice that &mut T is not Copy. Two live copies of a mutable reference would break the rule that mutable access is exclusive.
fn main() {
let pair = (1, 'x');
let copy = pair;
println!("{:?} {:?}", pair, copy);
let maybe: Option<u8> = Some(7);
let again = maybe;
println!("{:?} {:?}", maybe, again);
let words: [&str; 2] = ["a", "b"];
let more = words;
println!("{:?} {:?}", words, more);
}All three assignments leave the original usable. A tuple of Copy types, an Option<u8>, and an array of &str are all Copy.
Clone-only types
Types that own heap memory can be cloned but not copied. The most common ones are String, Vec<T>, Box<T>, HashMap<K, V>, HashSet<T>, and BTreeMap<K, V>. Their Clone implementations are conditional. Vec<T> is Clone only when T is Clone, and Option<String> is Clone but not Copy.
Some types are neither. std::fs::File and MutexGuard represent a unique resource. File does have try_clone, which asks the operating system for a new handle and can fail, so it is a method instead of the Clone trait. &mut T is also neither.
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<String, Vec<u32>> = HashMap::new();
scores.insert(String::from("ada"), vec![90, 85]);
let snapshot = scores.clone();
scores.get_mut("ada").unwrap().push(70);
println!("{:?}", scores["ada"]);
println!("{:?}", snapshot["ada"]);
}The clone is a deep copy. Changing scores afterwards does not affect snapshot, so the program prints [90, 85, 70] and then [90, 85].
Shared ownership is Clone, not Copy
Rc<T> and Arc<T> are Clone for every T, even when T itself is not Clone. Cloning increments a reference count and copies a pointer. They are never Copy, because the count must be updated on each duplicate, and a bitwise copy would skip that step.
use std::rc::Rc;
struct NoClone(u32);
fn main() {
let a = Rc::new(NoClone(5));
let b = Rc::clone(&a);
println!("{} {}", a.0, Rc::strong_count(&b));
}NoClone does not implement Clone, yet Rc<NoClone> can be cloned. The program prints 5 2.
How a bound propagates
Generic wrappers usually pass the trait through only when their contents have it. You can check a guess by writing a function that demands the trait.
fn needs_copy<T: Copy>(_: T) {}
fn needs_clone<T: Clone>(_: T) {}
fn main() {
needs_copy((1u8, 2.5f32));
needs_clone(vec![String::from("x")]);
// needs_copy(String::new()); // error: the trait bound `String: Copy` is not satisfied
}If the compiler accepts the call, the type has the trait. This is also a quick way to explore types you are unsure about.
Exercise
Is Option<Vec<i32>> Copy? Is it Clone? Is &mut i32 either?
Show answer
Option<Vec<i32>> is not Copy, because Vec<i32> owns heap memory. It is Clone, because Vec<i32> is Clone and Option<T> is Clone when T is. &mut i32 is neither, because duplicating a mutable reference would allow two live mutable accesses to the same data.