Borrowing

Most of the time, we’d like to access data without taking ownership over
it. To accomplish this, Rust uses a borrowing mechanism. Instead of
passing objects by value (T), objects can be passed by reference (&T).

The compiler statically guarantees (via its borrow checker) that references
always point to valid objects. That is, while references to an object
exist, the object cannot be destroyed.

  1. // This function takes ownership of a box and destroys it
  2. fn eat_box_i32(boxed_i32: Box<i32>) {
  3. println!("Destroying box that contains {}", boxed_i32);
  4. }
  5. // This function borrows an i32
  6. fn borrow_i32(borrowed_i32: &i32) {
  7. println!("This int is: {}", borrowed_i32);
  8. }
  9. fn main() {
  10. // Create a boxed i32, and a stacked i32
  11. let boxed_i32 = Box::new(5_i32);
  12. let stacked_i32 = 6_i32;
  13. // Borrow the contents of the box. Ownership is not taken,
  14. // so the contents can be borrowed again.
  15. borrow_i32(&boxed_i32);
  16. borrow_i32(&stacked_i32);
  17. {
  18. // Take a reference to the data contained inside the box
  19. let _ref_to_i32: &i32 = &boxed_i32;
  20. // Error!
  21. // Can't destroy `boxed_i32` while the inner value is borrowed.
  22. eat_box_i32(boxed_i32);
  23. // FIXME ^ Comment out this line
  24. // `_ref_to_i32` goes out of scope and is no longer borrowed.
  25. }
  26. // `boxed_i32` can now give up ownership to `eat_box` and be destroyed
  27. eat_box_i32(boxed_i32);
  28. }