Sub topic 5
Copy types and explicit Clone
This chapter assumes you know basic Rust syntax, can run programs with cargo, and understand that a move transfers ownership of a value. Here you learn when assignment copies a value instead of moving it, and how to duplicate a value on purpose.
Why some assignments don't move
A move would make the old variable unusable. For small values stored entirely on the stack, such as integers, that restriction adds nothing. Copying an i32 is as cheap as moving it, and no heap memory is at risk of being freed twice.
Rust marks these types with the Copy trait. Assigning a Copy value duplicates its bits, and both variables stay valid. A String owns heap memory, so it is not Copy. Assigning it moves it.
fn main() {
let a = 5;
let b = a;
println!("{a} {b}");
let s1 = String::from("hi");
let s2 = s1.clone();
println!("{s1} {s2}");
}The integers stay valid after the assignment. The String needs an explicit clone to keep both variables.
Which types are Copy
- All integer, floating-point,
bool, andchartypes. - Shared references (
&T). - Tuples and arrays whose elements are all
Copy. - Your own types, if you opt in.
String, Vec<T>, and Box<T> are not Copy. &mut T is not Copy either, because two live mutable references to one value would break the borrowing rules.
Clone: explicit duplication
Clone is a trait with a clone method. It can run arbitrary code, and for String that means allocating new heap memory and copying the bytes. Because that can be expensive, Rust never does it implicitly. You must write .clone(), which makes the cost visible when you read the code.
Every Copy type is also Clone. For a Copy type, clone is just a bitwise copy.
Deriving the traits
You can derive both traits on your own types. Copy requires Clone, so derive them together.
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug, Clone)]
struct User {
name: String,
id: u32,
}
fn main() {
let p = Point { x: 1, y: 2 };
let q = p;
println!("{:?} {:?}", p, q);
let u = User { name: String::from("Ada"), id: 1 };
let v = u.clone();
println!("{:?} {:?}", u, v);
}Deriving Copy on User would fail to compile, because String is not Copy. A type can be Copy only if all of its fields are.
Common errors
- Using a variable after a move. The message "borrow of moved value" means the type is not
Copy. Borrow with&, or clone if you really need two owners. - Adding
.clone()to silence the compiler. This works, but it hides a cost. Try a reference first. - Deriving
Copyon a type with aStringorVecfield. RemoveCopyand keepClone.
How the pieces relate
Exercise
Will this compile? If not, give two ways to fix it. let v1 = vec![1, 2, 3]; let v2 = v1; println!("{:?} {:?}", v1, v2);
Show answer
It does not compile. Vec is not Copy, so let v2 = v1; moves the vector and v1 is invalid afterwards. Fix 1: write let v2 = v1.clone(); so each variable owns its own vector. Fix 2: borrow instead with let v2 = &v1; so both names can read the same data.
Exercise
Why can #[derive(Clone, Copy)] be applied to a struct with two f64 fields but not to one with a String field?
Show answer
A type can be Copy only if every field is Copy. f64 is Copy. String owns heap memory, so duplicating it requires an allocation, which Copy does not allow. Such a struct can still derive Clone.