Sub topic 2
Copy: values that duplicate implicitly
This chapter assumes you know Rust structs, enums and traits, and the basic ownership rules (one owner, borrowing with & and &mut). You should also be able to read a compiler error. Here you will learn what the Copy trait changes about assignment, which types have it, and what rules limit it.
What Copy changes
By default, assigning a value to a new variable moves it. The old variable can no longer be used. Copy is the exception. A type that implements Copy is duplicated on assignment, and both variables stay valid.
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}");
}i32 is Copy, so a survives let b = a;. String is not Copy, so let t = s; moves the value and s is dead.
Copy is a marker trait. Its definition has no methods:
pub trait Copy: Clone {}Nothing calls a copy() function. The trait tells the compiler that a bitwise duplicate of the value is a valid, independent value. When the compiler sees a use of such a value, it copies the bytes (a memcpy) and leaves the original untouched. Because you can't write any code for this copy, you also can't change how it behaves.
The : Clone after Copy is a supertrait bound. Every Copy type must also implement Clone. The next chapters cover Clone in detail.
Where implicit copies happen
A copy happens anywhere a move would happen for a non-Copy type:
- Assignment:
let b = a; - Passing an argument:
f(a) - Returning a value from a function
- Binding a pattern, for example
let (x, y) = pair; - Capturing a variable in a
moveclosure - Reading a field or index, such as
let first = v[0];
The last case shows why Copy matters in everyday code. Indexing a Vec does not give you ownership of the element. It only lets you read it. For a Copy element, the read produces a copy. For a non-Copy element, it fails.
fn main() {
let nums = vec![10, 20, 30];
let first = nums[0];
println!("{first} {:?}", nums);
let names = vec![String::from("Ada"), String::from("Grace")];
// let n = names[0]; // error: cannot move out of index of `Vec<String>`
let n = &names[0];
println!("{n}");
}With Vec<String> you borrow with &names[0] or duplicate with .clone().
Which types are Copy
The standard library implements Copy for types whose entire value is the bytes stored inline:
| Type | Copy? | Reason |
|---|---|---|
| `i8` to `i128`, `u8` to `u128`, `isize`, `usize` | Yes | Plain integers |
| `f32`, `f64` | Yes | Plain floats |
| `bool`, `char` | Yes | Plain scalar values |
| `&T` | Yes | A shared reference is a pointer, and many shared references may exist |
| `&mut T` | No | Two live mutable references would break aliasing rules |
| `*const T`, `*mut T` | Yes | Raw pointers are just addresses |
| `fn` pointers, such as `fn(i32) -> i32` | Yes | Just an address |
| `()` and `!` | Yes | No data |
| Tuples `(A, B)` and arrays `[T; N]` | Only if every element type is `Copy` | Copy is inherited from the parts |
| `String`, `Vec<T>`, `Box<T>` | No | They own heap memory |
| `Rc<T>`, `Arc<T>` | No | Duplicating the pointer needs a count update, so it must be an explicit `clone` |
Tuples and arrays are the "all or nothing" cases. (i32, f64) is Copy. (i32, String) is not.
fn sum(values: [i32; 3]) -> i32 {
values.iter().sum()
}
fn main() {
let v = [1, 2, 3];
let total = sum(v);
println!("{total} {:?}", v);
}Passing v by value copies the array, so v is still usable afterward. Change the element type to String and the same program no longer compiles.
Shared references are Copy, mutable references are not
&T is Copy because a shared reference only allows reading. Any number of them can coexist.
fn main() {
let s = String::from("hi");
let r1 = &s;
let r2 = r1;
println!("{r1} {r2} {s}");
}r2 = r1 copies the pointer, not the String. The string data is never touched.
&mut T is not Copy, because two copies would give two live mutable paths to the same data. You can still pass a &mut to several functions in a row. The compiler inserts an implicit reborrow when the parameter type is known to be &mut:
fn bump(n: &mut i32) {
*n += 1;
}
fn main() {
let mut x = 0;
let r = &mut x;
bump(r);
bump(r);
println!("{x}");
}This prints 2. Each call borrows *r for a short time instead of moving r. Reborrowing is not copying.
Deriving Copy on your own types
Your own types are never Copy unless you ask. You opt in with derive, and you must derive Clone alongside it because of the supertrait.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn shift(mut p: Point) -> Point {
p.x += 10;
p
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = shift(a);
println!("{:?} {:?}", a, b);
}The output is Point { x: 1, y: 2 } Point { x: 11, y: 2 }. The function received its own copy, so mutating p did not affect a. Without Copy, the call shift(a) would move a, and the final println! would not compile.
Fieldless enums are another good fit:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
North,
East,
South,
West,
}
fn turn_right(d: Direction) -> Direction {
match d {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
}
}
fn main() {
let d = Direction::North;
let e = turn_right(d);
println!("{:?} {:?}", d, e);
}When a type cannot be Copy
The compiler enforces two rules. If either fails, impl Copy or #[derive(Copy)] is an error.
- Every field must be
Copy. OneString,VecorBoxfield makes the whole type non-Copy. For a generic struct, the derive adds aT: Copybound, soWrapper<i32>isCopyandWrapper<String>is not. - The type must not implement
Drop. A type with a destructor owns something that must be released exactly once. A bitwise copy would run the destructor twice.
// #[derive(Clone, Copy)] // error[E0184]: the trait `Copy` cannot be implemented for this type; the type has a destructor
struct Handle {
id: u32,
}
impl Drop for Handle {
fn drop(&mut self) {
println!("closing handle {}", self.id);
}
}
fn main() {
let h = Handle { id: 7 };
let g = h;
println!("moved handle {}", g.id);
}This program compiles because Handle is not Copy. The assignment let g = h; is a move, and "closing handle 7" prints once at the end of main.
The same reasoning excludes any type that owns a resource: file handles, locks, sockets, heap boxes. For these, a safe duplicate needs real work (allocating, reference counting). That is what Clone is for.
Copy is a semantic promise, not a speed guarantee
"Copy" does not mean "cheap". It means "a bitwise duplicate is valid". An array of a million bytes is Copy, and passing it by value copies a megabyte each time.
fn checksum(buf: [u8; 1_000_000]) -> u64 {
buf.iter().map(|&b| b as u64).sum()
}
fn main() {
let buf = [1u8; 1_000_000];
let a = checksum(buf);
let b = checksum(buf);
println!("{a} {b}");
}This compiles and runs, and the second call silently copies the whole array again. Take &[u8] to avoid it. A good rule of thumb is to keep Copy types to a few machine words, such as 16 to 32 bytes. Pass anything larger by reference.
Copy and API stability
Deriving Copy is a public promise. If your library type is Copy, callers will write code that relies on a staying usable after let b = a;. Removing Copy later breaks that code. Adding Copy to a type that did not have it is generally safe for callers. Because of this asymmetry, library authors hesitate to derive Copy on structs that might gain a String or Vec field later.
A decision flow for assignment
Summary
Copyis a marker trait. It makes assignment and argument passing duplicate the bytes instead of moving ownership.- Scalars, shared references, raw pointers, function pointers, and tuples or arrays of
Copytypes areCopy.&mut Tand owning types are not. - Derive
Copytogether withClone. Every field must beCopy, and the type must not implementDrop. Copymeans a bitwise duplicate is valid. It does not mean the copy is small.
Exercise
Which of these types can derive Copy, and why? (a) struct A { n: u8, flag: bool } (b) struct B { name: String } (c) struct C<'a> { text: &'a str } (d) struct D { v: [f32; 4], tag: (u8, char) } (e) a struct with only u32 fields that also implements Drop.
Show answer
(a), (c) and (d) can. (a) has only scalar fields. (c) holds a &str, and shared references are Copy. (d) has an array and a tuple whose elements are all Copy. (b) cannot because String owns heap memory. (e) cannot because a type with a Drop implementation is never allowed to be Copy, even when every field is Copy.
Exercise
The function fn describe(p: Point) takes a non-Copy struct Point by value. The caller writes describe(p); describe(p); and gets "use of moved value". Give two different fixes and say what each one changes.
Show answer
First, derive Clone and Copy on Point if all its fields are Copy. Each call then receives its own implicit copy. Second, change the signature to fn describe(p: &Point) and call describe(&p). The function then borrows, and nothing is duplicated or moved. A third option is to call describe(p.clone()), which duplicates explicitly and requires Clone.