Search⌘ K

Clone and Derive

Explore how to manage ownership and avoid errors by using the Clone trait in Rust. Understand manual implementation and automatic deriving to simplify code duplication tasks with structs and type parameters.

We'll cover the following...

We’ve seen the clone() method for Strings as a way to create a duplicate of an owned String. In some cases, this can be relevant for dealing with ownership issues. As a reminder, this code fails due to usage of a moved value:

Rust 1.40.0
struct Fruit {
apples: i32,
bananas: i32,
}
// Should use a reference, but I'm proving a point
fn print_fruit(fruit: Fruit) {
println!("Apples: {}, bananas: {}", fruit.apples, fruit.bananas);
}
fn main() {
let mut fruit = Fruit { apples: 5, bananas: 10 };
print_fruit(fruit); // moved here
fruit.apples *= 2; // this will fail
fruit.bananas *= 3;
print_fruit(fruit);
}

We can fix this by ...