Sub topic 1
Rust Copy and Clone: Duplicating Values Implicitly and Explicitly
Prerequisites
Assume you know Rust structs, functions, traits, ownership, borrowing, and basic Cargo usage. Rust’s compiler checks whether each value still has an owner.
Moves: What Happens When You Assign a Value
An assignment transfers ownership unless the value’s type implements Copy. This transfer is called a move. After a move, the original binding cannot be used because it no longer owns the value.
String owns heap-allocated text, so moving it transfers that ownership:
fn main() {
let first = String::from("hello");
let second = first;
// println!("{first}"); // error: borrow of moved value: `first`
println!("{second}");
}A move does not necessarily copy the heap data. Rust changes which binding owns the allocation, then prevents use of the old binding.
Copy: Values That Duplicate Implicitly
Copy is a marker trait for small values that can be duplicated with a simple bit-for-bit copy. Assignment and function calls copy these values automatically.
Integers, floating-point numbers, bool, char, and references are common Copy types.
fn main() {
let a = 5;
let b = a;
println!("{a} {b}"); // Both bindings remain valid.
}Copy is implicit. You cannot call a method to request this particular operation, and a type cannot customize what its implicit copy does.
Clone: Duplicating Explicitly with `.clone()`
Clone provides an explicit duplication operation. Calling .clone() can perform work such as allocating memory and copying heap data.
fn main() {
let original = String::from("hello");
let duplicate = original.clone();
println!("{original} {duplicate}");
}A type can implement Clone without implementing Copy. String is an example. Cloning it creates independent text, while moving it transfers one allocation.
Copy Versus Clone Side by Side
| Trait | How duplication happens | Typical cost |
|---|---|---|
| `Copy` | Implicitly during assignment | Small, fixed-size bit copy |
| `Clone` | Explicitly with `.clone()` | Type-dependent; may allocate |
Exercise
After let b = a;, when can both a and b be used?
Show answer
When a has a type that implements Copy; otherwise the assignment moves the value and a is no longer usable.