Rs
Module 2Ownership CoreLesson 3 of 918 min

Copy, Clone & Drop

When values duplicate cheaply, when clone is explicit, and when drop runs.

Copy vs Clone

  • Copy: implicit bitwise copy (cheap, stack-ish types)
  • Clone: explicit .clone() — may allocate
rust
#[derive(Copy, Clone, Debug)]
struct TickSize {
    cents: i32,
}

You can only derive Copy if all fields are Copy — so a struct with String cannot be Copy.

Drop

When a value goes out of scope, Rust runs its destructor. For String, that frees the heap buffer. You rarely implement Drop yourself at first — but knowing it runs at } explains why dangling pointers can’t exist in safe Rust.

Example

rust
fn main() {
    {
        let s = String::from("temp");
        println!("{s}");
    } // s dropped here
    println!("after scope");
}
Output
temp
after scope

Exercise

Define a Copy quote-tick struct and pass it around freely.

Challenge

Add a NonCopyOrder { ticker: String, qty: i64 } and show it does NOT implement Copy.

Tips
  • Integer tick prices often use i64 cents — Copy friendly
  • String fields block Copy
  • Drop is automatic — no free() calls

Try it live

Copy, Clone & DropRust 2021
Loading editor…
Output
Press Run to compile and execute.