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;
  4. // A tuple struct with resources that implements the `Clone` trait
  5. #[derive(Clone, Debug)]
  6. struct Pair(Box<i32>, Box<i32>);
  7. fn main() {
  8. // Instantiate `Nil`
  9. let nil = Nil;
  10. // Copy `Nil`, there are no resources to move
  11. let copied_nil = nil;
  12. // Both `Nil`s can be used independently
  13. println!("original: {:?}", nil);
  14. println!("copy: {:?}", copied_nil);
  15. // Instantiate `Pair`
  16. let pair = Pair(Box::new(1), Box::new(2));
  17. println!("original: {:?}", pair);
  18. // Copy `pair` into `moved_pair`, moves resources
  19. let moved_pair = pair;
  20. println!("copy: {:?}", moved_pair);
  21. // Error! `pair` has lost its resources
  22. //println!("original: {:?}", pair);
  23. // TODO ^ Try uncommenting this line
  24. // Clone `moved_pair` into `cloned_pair` (resources are included)
  25. let cloned_pair = moved_pair.clone();
  26. // Drop the original pair using std::mem::drop
  27. drop(moved_pair);
  28. // Error! `moved_pair` has been dropped
  29. //println!("copy: {:?}", moved_pair);
  30. // TODO ^ Try uncommenting this line
  31. // The result from .clone() can still be used!
  32. println!("clone: {:?}", cloned_pair);
  33. }