Clone and Copy in Rust
Copy types duplicate silently; everything else moves unless you ask for a clone.
fn main() {
let a = 7;
let b = a;
println!("{a} and {b} both fine");
let owned = String::from("tours");
let copy = owned.clone();
println!("{owned} / {copy}");
let moved = owned;
println!("{moved} now holds it");
let list = vec![1, 2, 3];
let same_again = list.clone();
println!("{:?} {:?}", list, same_again);
}
How it works
- Integers are
Copy, so assignment leaves the original usable. - A
Stringmoves, andcloneis the explicit deep copy. clonecosts an allocation — that is why it is not implicit.
Keywords and builtins used here
Stringfnletmain
The run, in numbers
- Lines
- 16
- Characters to type
- 315
- Tokens
- 95
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 63 seconds.
Step 2 of 3 in Move & clone, step 2 of 15 in Ownership & borrowing.