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 }
  2. fn main() {
  3. let mut point = Point { x: 0, y: 0, z: 0 };
  4. {
  5. let borrowed_point = &point;
  6. let another_borrow = &point;
  7. // Data can be accessed via the references and the original owner
  8. println!("Point has coordinates: ({}, {}, {})",
  9. borrowed_point.x, another_borrow.y, point.z);
  10. // Error! Can't borrow point as mutable because it's currently
  11. // borrowed as immutable.
  12. //let mutable_borrow = &mut point;
  13. // TODO ^ Try uncommenting this line
  14. // Immutable references go out of scope
  15. }
  16. {
  17. let mutable_borrow = &mut point;
  18. // Change data via mutable reference
  19. mutable_borrow.x = 5;
  20. mutable_borrow.y = 2;
  21. mutable_borrow.z = 1;
  22. // Error! Can't borrow `point` as immutable because it's currently
  23. // borrowed as mutable.
  24. //let y = &point.y;
  25. // TODO ^ Try uncommenting this line
  26. // Error! Can't print because `println!` takes an immutable reference.
  27. //println!("Point Z coordinate is {}", point.z);
  28. // TODO ^ Try uncommenting this line
  29. // Ok! Mutable references can be passed as immutable to `println!`
  30. println!("Point has coordinates: ({}, {}, {})",
  31. mutable_borrow.x, mutable_borrow.y, mutable_borrow.z);
  32. // Mutable reference goes out of scope
  33. }
  34. // Immutable references to point are allowed again
  35. let borrowed_point = &point;
  36. println!("Point now has coordinates: ({}, {}, {})",
  37. borrowed_point.x, borrowed_point.y, borrowed_point.z);
  38. }