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 }
4. fn main() {
5. let c = 'Q';
7. // A `ref` borrow on the left side of an assignment is equivalent to
8. // an `&` borrow on the right side.
9. let ref ref_c1 = c;
10. let ref_c2 = &c;
12. println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);
14. let point = Point { x: 0, y: 0 };
16. // `ref` is also valid when destructuring a struct.
17. let _copy_of_x = {
18. // `ref_to_x` is a reference to the `x` field of `point`.
19. let Point { x: ref ref_to_x, y: _ } = point;
21. // Return a copy of the `x` field of `point`.
22. *ref_to_x
23. };
25. // A mutable copy of `point`
26. let mut mutable_point = point;
28. {
29. // `ref` can be paired with `mut` to take mutable references.
30. let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;
32. // Mutate the `y` field of `mutable_point` via a mutable reference.
33. *mut_ref_to_y = 1;
34. }
36. println!("point is ({}, {})", point.x, point.y);
37. println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y);
39. // A mutable tuple that includes a pointer
40. let mut mutable_tuple = (Box::new(5u32), 3u32);
42. {
43. // Destructure `mutable_tuple` to change the value of `last`.
44. let (_, ref mut last) = mutable_tuple;
45. *last = 2u32;
46. }
48. println!("tuple is {:?}", mutable_tuple);
49. }
