Rust

Clone vs Copy — When to Use Each

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Stack-allocated primitives implement `Copy` (auto-duplicated). Heap-owning types like `String` and `Vec` only implement `Clone` (you must explicitly call `.clone()` to opt into the deep copy cost).
Rust
Raw
fn main() {
    // i32 is Copy — assignment duplicates the value
    let a: i32 = 42;
    let b = a;
    println!("{a} {b}");   // both still valid: 42 42

    // String is NOT Copy — assignment moves
    let s1 = String::from("hello");
    let s2 = s1;
    // println!("{s1}");   // ❌ moved
    println!("{s2}");

    // Use .clone() when you actually want a duplicate
    let s3 = String::from("hello");
    let s4 = s3.clone();
    println!("{s3} {s4}");

    // Derive Copy + Clone on your own struct (only if every field is Copy)
    #[derive(Copy, Clone, Debug)]
    struct Point { x: f64, y: f64 }
    let p = Point { x: 1.0, y: 2.0 };
    let q = p;             // copied, not moved
    println!("{p:?} {q:?}");
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.