Programming Languages
Rust
Subjective
Oct 04, 2025
What is the difference between Copy and Clone traits?
Detailed Explanation
Copy vs Clone traits:
• Copy: Implicit bitwise copy, no heap allocation
• Clone: Explicit deep copy, can involve heap allocation
• Copy implies Clone automatically
• Copy types: integers, floats, booleans, chars, tuples/arrays of Copy types
• Non-Copy types: String, Vec, HashMap, etc.
Copy trait:
• Marker trait (no methods)
• Automatic bitwise copy
• Move semantics disabled
• Stack-only data
• Cannot implement Drop
Clone trait:
• Explicit clone() method
• Can be expensive
• Deep copy semantics
• Works with heap data
Example:
#[derive(Copy, Clone)]
struct Point {
x: i32,
y: i32,
}
#[derive(Clone)]
struct Person {
name: String,
age: u32,
}
fn main() {
// Copy types
let p1 = Point { x: 1, y: 2 };
let p2 = p1; // Copied, p1 still valid
println!("p1: ({}, {})", p1.x, p1.y);
// Clone types
let person1 = Person {
name: "Alice".to_string(),
age: 30,
};
let person2 = person1.clone(); // Explicit clone
// person1 still valid after clone
println!("person1: {}", person1.name);
// String example
let s1 = String::from("hello");
let s2 = s1.clone(); // Explicit clone needed
println!("s1: {}, s2: {}", s1, s2);
}
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts