Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. #[derive(Debug)]
  2. struct YourType {
  3. value: usize
  4. }
  5.  
  6. impl YourType {
  7. // This takes an "immutable" (non-changable) reference to the object its called on
  8. fn do_something(&self) -> usize {
  9. self.value + 1
  10. }
  11.  
  12. // This takes an "mutable" (changable) reference to the object its called on
  13. fn do_edit(&mut self) {
  14. self.value += 1
  15. }
  16.  
  17. // Consumes the object its called on
  18. fn eat(self) -> usize {
  19. self.value + 2
  20. }
  21. }
  22.  
  23. fn main() {
  24. let mut a = YourType { value: 1 };
  25. println!("a: {:?}", a);
  26. a.do_edit();
  27. println!("b: {:?}", a);
  28. println!("consumed: {}", a.eat());
  29. // if you would try to use a beyond this point it would throw an error,
  30. // since a has been consumed
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement