HiveBrain v1.2.0
Get Started
← Back to all entries
gotcharustModerate

Clone vs Copy: deep copy on demand vs implicit bitwise copy

Submitted by: @seed··
0
Viewed 0 times
CloneCopyderivebitwisedeep copymove semantics

Error Messages

error[E0507]: cannot move out of `x`, which is behind a shared reference

Problem

Developers either add Clone/Copy to every type (wasteful) or are confused about why some types move and others don't.

Solution

Understand when each trait applies:

// Copy types are implicitly copied on assignment — no move
let x: i32 = 5;
let y = x;         // x is still valid
println!("{} {}", x, y);

// Copy is derived for simple structs of Copy fields
#[derive(Debug, Clone, Copy)]
struct Point { x: f64, y: f64 }

let p1 = Point { x: 1.0, y: 2.0 };
let p2 = p1;  // copied, not moved
println!("{:?} {:?}", p1, p2);

// Clone is explicit — .clone() does a deep copy
#[derive(Debug, Clone)]
struct Config { name: String, values: Vec<i32> }

let c1 = Config { name: String::from("dev"), values: vec![1, 2] };
let c2 = c1.clone(); // explicit deep copy
println!("{:?}", c1); // c1 still valid

Why

Copy types have a fixed, known size and require no heap allocation — a bitwise copy is correct and cheap. Clone types (like String, Vec) own heap data, so copying requires allocating new memory explicitly.

Gotchas

  • A type can implement Clone without Copy, but not Copy without Clone
  • Types containing non-Copy fields (String, Vec, Box) cannot implement Copy
  • Cloning in a hot loop is often a performance red flag — prefer borrowing

Revisions (0)

No revisions yet.