Answer#
Three different things can happen when you write let b = a;:
- Move: the default.
bnow owns the value andais unusable. Nothing is copied at run time, only ownership changes. - Copy: for types that implement the
Copytrait. Bothaandbstay valid. Only types that are trivial to duplicate can beCopy: numbers,bool,char, shared references, and your own structs made only of such things. - Clone: not automatic. You call
.clone()and get an independent duplicate, which for aStringorVecallocates and copies the contents.
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug, Clone)]
struct Player {
name: String,
at: Point,
}
fn main() {
let a = Point { x: 1, y: 2 };
let b = a; // Copy: both stay usable
println!("{a:?} {b:?}");
let p = Player { name: "Ada".into(), at: a };
let q = p.clone(); // Clone: an explicit, possibly costly copy
let r = p; // move: `p` can no longer be used
println!("{} {} {}", q.name, r.name, r.at.x);
}Point { x: 1, y: 2 } Point { x: 1, y: 2 }
Ada Ada 1How to decide#
- You need the original afterwards: pass a reference (
&value) if the receiver only reads, or.clone()if it must own its own copy. - Your small struct is only numbers: add
#[derive(Clone, Copy)]and it behaves like a number. - A type that owns heap memory or a resource (
String,Vec, a file handle) cannot beCopy, because two owners would free the same memory.
Common mistakes#
- Cloning to silence a borrow checker error without asking why. Sometimes it is right, but often the function should take a reference.
- Expecting
#[derive(Copy)]to work on a struct that contains aString. It does not compile.
Related questions#
Why does println!("{name}") not move name?#
Formatting macros take their arguments by reference. They read the value and leave it where it is.