Sub topic 2
Deriving Clone and Copy on Your Own Types
Assume you know Rust structs, traits, ownership, borrowing, and basic Cargo use. Rust lets you derive common trait implementations when their behavior follows directly from a type’s fields.
Deriving `Clone` and `Copy`
Clone provides explicit duplication through .clone(). Copy allows implicit duplication during assignment, argument passing, and returns. A type that implements Copy must also implement Clone, so derive both together when appropriate.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
let q = p;
println!("{p:?} {q:?}");
}The assignment to q copies p, so both bindings remain usable. Deriving Clone also permits p.clone().
For an enum, every stored field must support the derived trait:
#[derive(Clone, Copy)]
enum Direction {
North,
Step { distance: u8 },
}When a Type Cannot Be `Copy`
A type cannot be Copy if it owns or contains a value that cannot be copied implicitly. String, Vec<T>, and most file or network handles are examples. They manage resources whose duplication needs an explicit decision.
#[derive(Debug, Clone)]
struct User {
id: u32,
name: String,
}
fn main() {
let user = User { id: 1, name: String::from("Ada") };
let backup = user.clone();
println!("{user:?} {backup:?}");
}Clone can perform a deep copy of the string. Do not add Copy just to remove compiler errors. Copying a resource-owning value could be expensive or misleading.
Standard Library Types
Primitive numbers, bool, char, tuples of Copy values, and shared references such as &T are usually Copy. String and Vec<T> are Clone but not Copy. Rc<T> and Arc<T> are also Clone: cloning them shares ownership by increasing a reference count instead of copying the owned data.
Exercise
Why can a struct containing String derive Clone but not Copy?
Show answer
String owns heap data. It can duplicate that data explicitly with Clone, but implicit Copy is not allowed for it.