The ref pattern

When doing pattern matching or destructuring via the let binding, the ref
keyword can be used to take references to the fields of a struct/tuple. The
example below shows a few instances where this can be useful:

  1. #[derive(Clone, Copy)]
  2. struct Point { x: i32, y: i32 }
  3. fn main() {
  4. let c = 'Q';
  5. // A `ref` borrow on the left side of an assignment is equivalent to
  6. // an `&` borrow on the right side.
  7. let ref ref_c1 = c;
  8. let ref_c2 = &c;
  9. println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);
  10. let point = Point { x: 0, y: 0 };
  11. // `ref` is also valid when destructuring a struct.
  12. let _copy_of_x = {
  13. // `ref_to_x` is a reference to the `x` field of `point`.
  14. let Point { x: ref ref_to_x, y: _ } = point;
  15. // Return a copy of the `x` field of `point`.
  16. *ref_to_x
  17. };
  18. // A mutable copy of `point`
  19. let mut mutable_point = point;
  20. {
  21. // `ref` can be paired with `mut` to take mutable references.
  22. let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;
  23. // Mutate the `y` field of `mutable_point` via a mutable reference.
  24. *mut_ref_to_y = 1;
  25. }
  26. println!("point is ({}, {})", point.x, point.y);
  27. println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y);
  28. // A mutable tuple that includes a pointer
  29. let mut mutable_tuple = (Box::new(5u32), 3u32);
  30. {
  31. // Destructure `mutable_tuple` to change the value of `last`.
  32. let (_, ref mut last) = mutable_tuple;
  33. *last = 2u32;
  34. }
  35. println!("tuple is {:?}", mutable_tuple);
  36. }