ミュータビリティ
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:
#[allow(dead_code)] #[derive(Clone, Copy)] struct Book { // `&'static str`はread-onlyメモリ上の文字列への参照。 author: &'static str, title: &'static str, year: u32, } // この関数はBook型への参照を取ります。 fn borrow_book(book: &Book) { println!("I immutably borrowed {} - {} edition", book.title, book.year); } // この関数はミュータブルなBook型へのミュータブルな参照を取り、 // `year`を2014へ変更します。 fn new_edition(book: &mut Book) { book.year = 2014; println!("I mutably borrowed {} - {} edition", book.title, book.year); } fn main() { // `immutabook`という名のイミュータブルなBookを作成。 let immutabook = Book { // 文字列リテラルは`&'static str`型になります。 author: "Douglas Hofstadter", title: "Gödel, Escher, Bach", year: 1979, }; // `immutabook`のミュータブルなコピーを作成し、`mutabook`と名付けます。 let mut mutabook = immutabook; // イミュータブルなオブジェクトをイミュータブルに借用します。 borrow_book(&immutabook); // ミュータブルなオブジェクトをイミュータブルに借用します。 borrow_book(&mutabook); // ミュータブルなオブジェクトをミュータブルに借用します。 new_edition(&mut mutabook); // エラー!イミュータブルなオブジェクトをミュータブルに借用できません。 new_edition(&mut immutabook); // FIXME ^ この行をコメントアウトしましょう }