Mutability

Mutable data can be mutably borrowed using &mut T. This is called
a mutable reference and gives read/write access to the borrower.
In contrast, &T borrows the data via an immutable reference, and
the borrower can read the data but not modify it:

  1. #[allow(dead_code)]
  2. #[derive(Clone, Copy)]
  3. struct Book {
  4. // `&'static str` is a reference to a string allocated in read only memory
  5. author: &'static str,
  6. title: &'static str,
  7. year: u32,
  8. }
  9. // This function takes a reference to a book
  10. fn borrow_book(book: &Book) {
  11. println!("I immutably borrowed {} - {} edition", book.title, book.year);
  12. }
  13. // This function takes a reference to a mutable book and changes `year` to 2014
  14. fn new_edition(book: &mut Book) {
  15. book.year = 2014;
  16. println!("I mutably borrowed {} - {} edition", book.title, book.year);
  17. }
  18. fn main() {
  19. // Create an immutable Book named `immutabook`
  20. let immutabook = Book {
  21. // string literals have type `&'static str`
  22. author: "Douglas Hofstadter",
  23. title: "Gödel, Escher, Bach",
  24. year: 1979,
  25. };
  26. // Create a mutable copy of `immutabook` and call it `mutabook`
  27. let mut mutabook = immutabook;
  28. // Immutably borrow an immutable object
  29. borrow_book(&immutabook);
  30. // Immutably borrow a mutable object
  31. borrow_book(&mutabook);
  32. // Borrow a mutable object as mutable
  33. new_edition(&mut mutabook);
  34. // Error! Cannot borrow an immutable object as mutable
  35. new_edition(&mut immutabook);
  36. // FIXME ^ Comment out this line
  37. }

See also:

static