Sub topic 5
Copy Types and Explicit Clone
This chapter assumes you know basic Rust syntax (variables, functions, structs, enums), can build and run a program with cargo, and understand moves from the previous chapter. You also need a general idea of the stack and the heap, and some familiarity with String, Vec, and &str.
By the end you should be able to predict whether an assignment or function call moves, copies, or clones a value. You should also be able to derive Copy and Clone correctly and avoid the common mistakes with both.
Two Ways a Value Can Be Duplicated
A move transfers ownership and invalidates the source. Some types behave differently. Assigning them leaves the original usable, because the compiler duplicates the bits instead of transferring ownership.
Rust has two duplication mechanisms:
- Copy is implicit. The compiler does it for you on every assignment, function call, or return. It is always a plain bitwise copy of the value, and you cannot customize it.
- Clone is explicit. You call
.clone(). It runs arbitrary code, which may allocate memory and may be expensive.
The design choice is deliberate. Cheap duplication happens silently. Costly duplication is always visible in the source.
Copy Types
A type is Copy if the standard library or you have implemented the Copy trait for it. Assigning a Copy value does not move it.
fn main() {
let a = 5;
let b = a;
println!("{a} {b}");
let s1 = String::from("hi");
let s2 = s1.clone();
println!("{s1} {s2}");
}Both a and b stay valid because i32 implements Copy. The String needs an explicit clone to keep both variables alive.
The standard types that implement Copy include:
| Type | Copy? | Why |
|---|---|---|
| `i32`, `u64`, `usize`, and other integers | Yes | Fixed-size bits on the stack |
| `f32`, `f64` | Yes | Fixed-size bits on the stack |
| `bool`, `char` | Yes | Fixed-size bits on the stack |
| `&T` (shared reference) | Yes | A pointer, copying it creates another reader |
| `&mut T` | No | Copying would create two writers |
| Tuples and arrays of `Copy` types | Yes | Copy if every element is Copy |
| `String`, `Vec<T>`, `Box<T>` | No | They own heap memory |
Shared references being Copy is what lets you pass &s to several functions in a row without any ceremony. Mutable references are not Copy, which protects the rule that only one &mut can exist at a time.
Why Heap-Owning Types Cannot Be Copy
A String holds a pointer, a length, and a capacity. A bitwise copy would produce two String values pointing at the same heap buffer. When both went out of scope, each would free the buffer, giving a double free.
Rust prevents this by refusing to let any type implement Copy if it, or any of its fields, implements Drop. The rule is not a style guideline. The compiler rejects it.
struct Handle {
id: u32,
}
impl Drop for Handle {
fn drop(&mut self) {
println!("closing {}", self.id);
}
}
// error[E0184]: the trait `Copy` cannot be implemented
// for this type; the type has a destructor
// #[derive(Clone, Copy)]
// struct Handle { id: u32 }
fn main() {
let h = Handle { id: 1 };
let moved = h;
println!("{}", moved.id);
}Here Handle is moved, not copied. Closing runs once, when moved goes out of scope.
Deriving Copy and Clone on Your Own Types
You opt in to Copy with a derive. Copy requires Clone as a supertrait, so you derive both together.
#[derive(Debug, Clone, Copy)]
struct Point {
x: f64,
y: f64,
}
fn shift(p: Point) -> Point {
Point { x: p.x + 1.0, ..p }
}
fn main() {
let a = Point { x: 0.0, y: 0.0 };
let b = shift(a);
println!("{a:?} {b:?}");
}shift takes p by value, but a is still usable afterwards because Point is Copy. A struct can derive Copy only if every field is Copy. Adding a String field to Point would make the derive fail to compile.
Copy is not free to add. It becomes part of your public API. If you later add a non-Copy field, every caller that relied on implicit copying breaks. Derive Copy only for small, plain-data types such as points, colors, ids, and flags.
Clone: Explicit Duplication
Clone has one method, clone(&self) -> Self. It takes a shared reference, so the original is untouched, and it returns an independent value.
For a String, clone allocates a new buffer and copies the bytes. For a Vec<String>, it clones every element, so the cost grows with the size of the data.
fn main() {
let names = vec![String::from("Ada"), String::from("Grace")];
let backup = names.clone();
let mut working = names;
working.push(String::from("Linus"));
println!("{backup:?}");
println!("{working:?}");
}After the clone, backup and working share nothing. Changing one never affects the other. This is called a deep copy, because the heap data is duplicated too.
Every Copy type is also Clone, and for those types clone is just the same bitwise copy. You rarely need to call it on them.
Reading the Compiler Error
The most common mistake is using a value after a move. The compiler message points to the move and suggests the fix.
fn consume(s: String) {
println!("{s}");
}
fn main() {
let s = String::from("data");
consume(s.clone());
consume(s);
}The first call receives a clone, so s survives. The second call moves s. Without the .clone(), the second line would produce error[E0382]: use of moved value: s, and the compiler would note that String does not implement Copy.
When Not to Clone
Adding .clone() makes borrow errors vanish, which makes it tempting. Treat it as a deliberate decision.
- If a function only reads the data, take
&Tor&strinstead of cloning. - If you clone inside a loop, check whether you can borrow or restructure.
- If you need several owners of the same large value,
RcorArcshares it without copying the data. Calling.clone()on anRconly increments a counter. Later chapters cover this.
Cloning is the right choice when you truly need an independent value. Examples are storing data beyond the lifetime of its source, sending it to another thread, or keeping a snapshot to compare against later.
Decision Summary
Exercise
A struct Config has fields retries: u32, verbose: bool, and name: String. A teammate writes #[derive(Clone, Copy)] on it. Will it compile? What are two ways to let callers keep using a Config after passing it to a function?
Show answer
It will not compile, because name: String is not Copy, and a type can derive Copy only if every field is Copy. To keep using a Config after passing it, either pass a reference (&Config) so the function only borrows it, or derive just Clone and call config.clone() at the call site so the function receives an independent copy.
Exercise
What does this program print, and why is a still usable on the line that prints it?
let a = (1, 2.5, 'x');
let b = a;
println!("{:?} {:?}", a, b);
Show answer
It prints (1, 2.5, 'x') (1, 2.5, 'x'). A tuple is Copy when every element is Copy, and i32, f64, and char all are. The assignment copies the tuple instead of moving it, so a remains valid.