Clone and Derive
We'll cover the following...
We’ve seen the clone()
method for String
s 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:
Press + to interact
struct Fruit {apples: i32,bananas: i32,}// Should use a reference, but I'm proving a pointfn 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 herefruit.apples *= 2; // this will failfruit.bananas *= 3;print_fruit(fruit);}
We can fix this by ...