Clone
When dealing with resources, the default behavior is to transfer them during assignments or function calls. However, sometimes we need to make a copy of the resource as well.
The Clone trait helps us do exactly this. Most commonly, we can
use the .clone() method defined by the Clone trait.
1. // A unit struct without resources
2. #[derive(Debug, Clone, Copy)]
3. struct Nil;
5. // A tuple struct with resources that implements the `Clone` trait
6. #[derive(Clone, Debug)]
7. struct Pair(Box<i32>, Box<i32>);
9. fn main() {
10. // Instantiate `Nil`
11. let nil = Nil;
12. // Copy `Nil`, there are no resources to move
13. let copied_nil = nil;
15. // Both `Nil`s can be used independently
16. println!("original: {:?}", nil);
17. println!("copy: {:?}", copied_nil);
19. // Instantiate `Pair`
20. let pair = Pair(Box::new(1), Box::new(2));
21. println!("original: {:?}", pair);
23. // Copy `pair` into `moved_pair`, moves resources
24. let moved_pair = pair;
25. println!("copy: {:?}", moved_pair);
27. // Error! `pair` has lost its resources
28. //println!("original: {:?}", pair);
29. // TODO ^ Try uncommenting this line
31. // Clone `moved_pair` into `cloned_pair` (resources are included)
32. let cloned_pair = moved_pair.clone();
33. // Drop the original pair using std::mem::drop
34. drop(moved_pair);
36. // Error! `moved_pair` has been dropped
37. //println!("copy: {:?}", moved_pair);
38. // TODO ^ Try uncommenting this line
40. // The result from .clone() can still be used!
41. println!("clone: {:?}", cloned_pair);
42. }
