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. }
10. // This function takes a reference to a book
11. fn borrow_book(book: &Book) {
12. println!("I immutably borrowed {} - {} edition", book.title, book.year);
13. }
15. // This function takes a reference to a mutable book and changes `year` to 2014
16. fn new_edition(book: &mut Book) {
17. book.year = 2014;
18. println!("I mutably borrowed {} - {} edition", book.title, book.year);
19. }
21. fn main() {
22. // Create an immutable Book named `immutabook`
23. let immutabook = Book {
24. // string literals have type `&'static str`
25. author: "Douglas Hofstadter",
26. title: "Gödel, Escher, Bach",
27. year: 1979,
28. };
30. // Create a mutable copy of `immutabook` and call it `mutabook`
31. let mut mutabook = immutabook;
33. // Immutably borrow an immutable object
34. borrow_book(&immutabook);
36. // Immutably borrow a mutable object
37. borrow_book(&mutabook);
39. // Borrow a mutable object as mutable
40. new_edition(&mut mutabook);
42. // Error! Cannot borrow an immutable object as mutable
43. new_edition(&mut immutabook);
44. // FIXME ^ Comment out this line
45. }
