Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ OWNERSHIP WITHOUT THE PANIC
BUILD NOTE 10 / 53

Choose when duplication is real.

Recognize implicit copies and make heap duplication intentional.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

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.

lessons/copy-clone/src/main.rs
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}");
}
↳ EXPECTED OUTPUT
7 7: Rust / Rust!
  1. 1

    The integer assignment copies.

  2. 2

    String::clone creates independently owned text.

  3. 3

    Changing second does not change first.

From the extracted rust-workbench folder
cargo run -p lesson_copy_clone

03 Mind the boundary

04 Your next build

A SMALL MISSION

Clone a vector, change only the clone, and assert that the original is unchanged.

Reveal one possible solution +
solutions/copy-clone/src/main.rs
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

QUICK SIGNAL CHECK

Does Clone always mean a deep copy of all underlying data?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.