Guest User

Untitled

a guest
Feb 16th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. // The clone() Function
  2.  
  3. // Clone types allow you to explicitly invoke a .clone() method.
  4. // This copies the contents to a new instance, but it can be expensive.
  5. // If it wasn't expensive, the type itself would be a copy type.
  6. // Use borrowing instead of clone if you can avoid it.
  7.  
  8. fn copy_and_display(x: i32) {
  9. println!("x = {}", x);
  10. }
  11.  
  12. fn move_and_display(s: String) {
  13. println!("s = {}", s);
  14. }
  15.  
  16. fn main() {
  17. let x = 5;
  18.  
  19. // x is a Copy Type, but all copy types are clone types.
  20. copy_and_display(x.clone());
  21.  
  22. // We can still print x, because it was copied into the function, not moved.
  23. println!("x = {}", x);
  24.  
  25. let s = String::from("this is a clone type");
  26.  
  27. // Here we move a clone of s into the function.
  28. move_and_display(s.clone());
  29.  
  30. // We can still display this, because only the clone was moved.
  31. println!("s = {}", s);
  32. }
Add Comment
Please, Sign In to add comment