Choose when duplication is real.
Recognize implicit copies and make heap duplication intentional.
01 Understand the contract
Small scalar types such as i32 implement Copy: assigning them leaves both values usable. A String does not implement Copy because it owns a heap buffer. clone explicitly creates another owned String and copies the text. Clone has type-specific behavior: cloning an Arc increments a reference count rather than deeply copying its payload. Read the type and its API before assuming what duplication costs. Borrow when you only need temporary access; clone when independent ownership is actually part of the design.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let a = 7;
let b = a;
let first = String::from("Rust");
let mut second = first.clone();
second.push('!');
println!("{a} {b}: {first} / {second}");
}7 7: Rust / Rust!
- 1
The integer assignment copies.
- 2
String::clone creates independently owned text.
- 3
Changing second does not change first.
cargo run -p lesson_copy_clone03 Mind the boundary
04 Your next build
Clone a vector, change only the clone, and assert that the original is unchanged.
Reveal one possible solution +
fn main() {
let original = vec![1, 2];
let mut copy = original.clone();
copy.push(3);
assert_eq!(original, [1, 2]);
assert_eq!(copy, [1, 2, 3]);
}05 Check your reasoning
Does Clone always mean a deep copy of all underlying data?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.