Sub topic 5
Deriving Clone and Copy on your own types
This chapter assumes you know Rust structs, enums, and traits, and that you have seen move errors from the compiler. It covers how to add Clone and Copy to your own types with #[derive], and what the compiler checks when you do.
What deriving does
A derive attribute asks the compiler to write a trait implementation for you. For Clone, the generated code calls clone on every field and builds a new value from the results. For Copy, the generated code is empty. Copy is a marker trait with no methods. It tells the compiler that a bitwise copy of the value is a valid duplicate.
Here is a struct that derives both traits:
#[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);
println!("{}", p == q);
}After let q = p;, the variable p is still usable because Point is Copy. Without Copy, the assignment would move p and the println! would fail to compile.
Derive Clone together with Copy
Copy has Clone as a supertrait. You cannot derive Copy alone. This fails:
#[derive(Copy)]
struct Point {
x: i32,
y: i32,
}The compiler reports that Point does not implement Clone. Always write #[derive(Clone, Copy)] as a pair when you want a copyable type.
For a Copy type, the derived Clone simply returns *self, so .clone() and plain assignment produce the same result.
Deriving on enums
Enums work the same way. Every variant's fields must satisfy the trait.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Direction {
North,
East,
South,
West,
}
fn turn_right(d: Direction) -> Direction {
match d {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
}
}
fn main() {
let d = Direction::North;
let e = turn_right(d);
println!("{:?} {:?}", d, e);
}Passing d into turn_right copies it, so d is still available on the next line. Small enums with no data are a very common use of Copy.
When deriving is not possible
The derive only succeeds if every field type implements the trait. For Clone, each field must be Clone. For Copy, each field must be Copy.
A String is Clone but not Copy, because it owns heap memory. A struct containing a String can therefore derive Clone only:
// #[derive(Clone, Copy)] // error: the trait `Copy` cannot be implemented for this type
#[derive(Debug, Clone)]
struct User {
id: u32,
name: String,
}
fn main() {
let u = User { id: 1, name: String::from("Ada") };
let v = u.clone();
println!("{:?} {:?}", u, v);
}The Copy line is commented out because it would not compile. The compiler points at the String field as the cause. Chapter "When a type cannot be Copy" covers the full list of restrictions.
Generic types get bounds
When you derive on a generic type, the compiler adds a bound on each type parameter. This code:
#[derive(Clone, Copy)]
struct Pair<T> {
a: T,
b: T,
}expands to an implementation that applies only when T: Clone (and T: Copy). So Pair<i32> is Copy, while Pair<String> is only Clone if you derive Clone. The bound is added even if no field actually needs it, for example when a field is PhantomData<T> or Rc<T>. In those cases, write the implementation by hand.
What the derive costs
| Derive | Generated behavior | Cost |
|---|---|---|
| `Clone` | Calls `clone` on each field | Depends on the fields |
| `Copy` | Marks the type as bitwise copyable | One memcpy on every use |
Deriving Copy on a large struct makes every assignment and function call copy all of its bytes. Keep Copy types small.
Exercise
A struct has fields id: u32 and tags: Vec<String>. Which of Clone and Copy can you derive, and why?
Show answer
Only Clone. u32 is both Clone and Copy, but Vec<String> is Clone and not Copy because it owns heap memory. Every field must be Copy for the derive to succeed, so Copy is rejected.