Move vs copy
Assignment in Rust moves by default: the source is invalid. Types that implement Copy are duplicated bitwise instead, and both names stay valid.
Detailed Explanation
let b = a; looks like a copy to a Java or Python programmer. For a String it is a move: the three words of pointer, length, and capacity go to b, and a may not be used. There is no reference count increment. There is no deep copy of the characters. The buffer has one owner, b.
Copy is a marker trait that changes that meaning. let b = a; for an i32 copies the bits; a is still usable. The compiler implements Copy for integers, floats, bool, char, shared references, and tuples/arrays of Copy types. A type that implements Drop cannot implement Copy: you cannot have two owners that will both free the same resource.
Moves are cheap when the value is a pointer-sized header (Vec, String, Box). They are memcpy of the whole value when the type is a large Copy array. Moves of non-Copy large structs are also memcpy of the struct's bytes; the expensive part is usually the heap those fields own, which is not duplicated.
Function calls move the same way. take(s) moves s if the parameter is String. take(&s) does not. Return values move out. The optimiser often elides copies of large values (RVO-like), but you should still not Copy a 4 KiB struct by accident.
When something moves: owned heap types, anything with a unique resource. When something copies: small values, &T, flags. When you need a second owned heap value: clone, not Copy.
Pattern matching moves by default the same way assignment does. match x { Y { s } => ... } moves s out of x when s is not Copy. Match on &x or use ref s if you need x afterwards. This is the same rule as let s = x.s and surprises people first in match, not in let.
Code Examples
fn main() {
let a = String::from("ada");
let b = a; // move
println!("{b}"); // prints: ada
let x = 3;
let y = x; // copy
println!("{x} {y}"); // prints: 3 3
}Common Gotchas
Using a moved value does not compile
Borrow it, clone it, or stop needing both names.
A large `Copy` type copies on every assign
`#[derive(Copy)]` on a 1 KiB struct is a performance trap. Leave it non-`Copy` and pass `&`.
Moves of `Vec` do not copy the buffer
Only the three-word header moves. That is why returning a `Vec` is cheap.
`Copy` implies `Clone`
The clone of a `Copy` type should be the same memcpy. You still write `.clone()` if you want the explicit form.