Clone / Copy Traits
The Clone trait provides a way to explicitly deep-copy values in Rust, while the Copy trait is a lightweight mechanism that automatically copies stack-based data.
Syntax
// Deriving and using Clone
#[derive(Clone)]
struct StructName { ... }
let copied = original.clone();
// Deriving Copy (Clone is also required)
#[derive(Clone, Copy)]
struct StructName { ... }
Clone / Copy Comparison
| Trait | Description |
|---|---|
| Clone | Duplicates a value by explicitly calling .clone(). Copies all data, including heap-allocated data. |
| Copy | Automatically copies the value on assignment or when passed to a function. Suitable for lightweight types that live entirely on the stack. |
| Copy-able types | Integers, floating-point numbers, bool, char, references (&T), and tuples/arrays of these types. |
| Non-Copy types | Types that own heap memory, such as String, Vec, and Box, cannot implement Copy. |
Sample Code
#[derive(Clone, Debug)]
struct Point {
x: f64,
y: f64,
}
#[derive(Clone, Copy, Debug)]
struct Color {
r: u8,
g: u8,
b: u8,
}
fn main() {
// Using Clone
let p1 = Point { x: 1.0, y: 2.0 };
let p2 = p1.clone(); // Explicitly clone the value.
println!("{:?}", p1); // p1 is still usable.
println!("{:?}", p2);
// Using Copy (automatic copy)
let c1 = Color { r: 255, g: 0, b: 0 };
let c2 = c1; // Automatically copied because Color implements Copy (not a move).
println!("{:?}", c1); // c1 is still usable.
println!("{:?}", c2);
// String does not implement Copy, so clone is required.
let s1 = String::from("hello");
let s2 = s1.clone();
println!("{} {}", s1, s2); // Both are usable.
// Primitive types implement Copy.
let x = 42;
let y = x; // Automatically copied.
println!("x={}, y={}", x, y);
}
Notes
Using the #[derive(Clone)] macro automatically generates an implementation that calls clone() on every field. If a field requires custom clone logic, implement the Clone trait manually.
The Copy trait cannot be used on types that implement the Drop trait. Types that own heap memory require Drop, which makes implementing Copy impossible.
For more on ownership and moving values, see Ownership / Move.
If you find any errors or copyright issues, please contact us.