Sub topic 2
Copy: values that duplicate implicitly
This chapter assumes you know basic Rust syntax (structs, enums, functions, traits), the ownership and borrowing basics, and how to read compiler errors. It covers the Copy trait: what it is, which types have it, and how it changes what assignment does.
What Copy means
Copy is a marker trait. It has no methods. A type that implements it tells the compiler: "duplicating my bits is a complete, safe copy, so the original stays valid."
Without Copy, assigning a value moves it, and the old binding can't be used again. With Copy, assignment duplicates the value and both bindings stay usable.
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 the assignment. String is not Copy, so s is moved into t. Using s afterwards is a compile error.
When copies happen
The copy is implicit. You write no .clone() call. It happens everywhere a value would otherwise move:
let b = a;- passing an argument:
f(a) - returning a value or assigning a struct field
- capturing a variable in a
moveclosure (the closure gets its own copy)
A copy is always a plain bitwise duplicate. You can't customize it, and it never runs your code. That is why Copy types are cheap in the sense that no allocation or side effect occurs, although a large Copy array still costs a memcpy of its full size.
Deriving Copy on your own types
Copy requires Clone as a supertrait, so you derive both together. Every field must itself be Copy.
#[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);
}Both p and q print. Without Copy in the derive list, p would be moved into q and the println! would fail to compile.
Which types are Copy
Types that are Copy in the standard library include:
- integers, floats,
bool, andchar - shared references
&T - raw pointers and function pointers
- tuples and arrays whose elements are all
Copy
Types that are not Copy include String, Vec<T>, Box<T>, and &mut T. A mutable reference can't be Copy because two live &mut to the same data would break the aliasing rules.
When a type cannot be Copy
A type can't be Copy if any field isn't. The usual cause is a field that owns a resource, such as heap memory. Copying the bits of a String would produce two owners of one buffer and a double free.
// #[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);
}A type also can't be both Copy and Drop. If a type has cleanup code, an implicit duplicate would run that cleanup twice.
Common mistakes
- Expecting a move error on a
Copytype. If code compiles when you expected a move, check whether the type isCopy. - Deriving
CopywithoutClone. The compiler rejects it becauseCloneis a supertrait. - Adding a
StringorVecfield to aCopystruct. The derive stops compiling, and every place that relied on implicit copying breaks. - Assuming
Copymeans small. A[u8; 1_000_000]isCopy, and each assignment copies a megabyte.
Exercise
A struct has fields id: u32 and tags: Vec<String>. Can you derive Copy for it? If not, what do you derive so you can still duplicate it, and how do you do it?
Show answer
No. Vec<String> is not Copy, and a Copy type needs every field to be Copy. Derive Clone instead and duplicate the value explicitly with .clone(). Plain assignment will move it.
Exercise
Why can't a type implement both Copy and Drop?
Show answer
Implicit duplication would create a second value, and both would run drop and release the same resource twice. The compiler forbids the combination.