Copy and Clone (Rust)

Copy and Clone are traits that let a type be duplicated. Copy gives implicit, cheap bit-for-bit copies on assignment (for stack types like integers); Clone gives an explicit, possibly expensive .clone() for heap types.

Rust

Types like i32, bool, char, and f64 implement Copy, so assigning them duplicates the value instead of moving it — the original stays usable. Copy only works for types that are entirely on the stack with no heap ownership.

Clone is the opt-in, explicit version: calling .clone() makes a full independent copy, including deep-copying any heap data. Because that can be costly (e.g. duplicating a large Vec), Rust makes you write it out so the cost is visible.

A type can derive both with #[derive(Clone, Copy)] when it only contains Copy fields. Heap-owning types like String and Vec implement Clone but not Copy — you must clone them explicitly, which is the compiler nudging you to consider borrowing instead.

Syntax

#[derive(Clone, Copy)]
struct Point { x: i32, y: i32 }

Examples

Rust

fn main() {
    let a = 5;
    let b = a;          // Copy: a still valid
    println!("{} {}", a, b);
    let s = String::from("hi");
    let t = s.clone();  // explicit deep copy
    println!("{} {}", s, t);
}

Output:

5 5
hi hi

Learn it in a lesson

See also

Back to the Dictionary