Copy Types and Clone

Updated

October 31, 2026

Copy Types and Clone

The Copy Trait

Types that live entirely on the stack and have fixed sizes implement the Copy trait. Assignment of Copy types performs a bitwise copy rather than a move:

fn main() {
    let x: i32 = 42;
    let y = x; // Bitwise copy
    println!("x = {}, y = {}", x, y); // Both valid!
}

The Clone Trait

For heap-allocated types where an explicit, potentially expensive deep copy is desired, use .clone():

fn main() {
    let s1 = String::from("records");
    let s2 = s1.clone(); // Deep allocation on heap
    println!("s1 = {}, s2 = {}", s1, s2); // Both valid
}