Aliasing

Data can be immutably borrowed any number of times, but while immutably borrowed, the original data can’t be mutably borrowed. On the other hand, only one mutable borrow is allowed at a time. The original data can be borrowed again only after the mutable reference goes out of scope.

1. struct Point { x: i32, y: i32, z: i32 }

3. fn main() {
4. let mut point = Point { x: 0, y: 0, z: 0 };

6. {
7. let borrowed_point = &point;
8. let another_borrow = &point;

10. // Data can be accessed via the references and the original owner
11. println!("Point has coordinates: ({}, {}, {})",
12. borrowed_point.x, another_borrow.y, point.z);

14. // Error! Can't borrow point as mutable because it's currently
15. // borrowed as immutable.
16. //let mutable_borrow = &mut point;
17. // TODO ^ Try uncommenting this line

19. // Immutable references go out of scope
20. }

22. {
23. let mutable_borrow = &mut point;

25. // Change data via mutable reference
26. mutable_borrow.x = 5;
27. mutable_borrow.y = 2;
28. mutable_borrow.z = 1;

30. // Error! Can't borrow `point` as immutable because it's currently
31. // borrowed as mutable.
32. //let y = &point.y;
33. // TODO ^ Try uncommenting this line

35. // Error! Can't print because `println!` takes an immutable reference.
36. //println!("Point Z coordinate is {}", point.z);
37. // TODO ^ Try uncommenting this line

39. // Ok! Mutable references can be passed as immutable to `println!`
40. println!("Point has coordinates: ({}, {}, {})",
41. mutable_borrow.x, mutable_borrow.y, mutable_borrow.z);

43. // Mutable reference goes out of scope
44. }

46. // Immutable references to point are allowed again
47. let borrowed_point = &point;
48. println!("Point now has coordinates: ({}, {}, {})",
49. borrowed_point.x, borrowed_point.y, borrowed_point.z);
50. }