13.3.1 Mutability
가변한 데이터는 &mut T
를 사용해 가변대여를 할 수 있다. 이는 가변 참조라고 불리고 읽고/쓰기 제어권을 대여자에게 전달한다. 대조적으로 &T
는 불가변 참조를 통해 데이터를 대여하고, 대여자는 데이터를 읽을 수는 있지만 수정할 수는 없다:
#[allow(dead_code)]
#[derive(Clone, Copy)]
struct Book {
// `&'static str`은 읽기 전용 메모리에 할당된 문자열의 참조이다.
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() {
// 불가변인 Book을 생성하고 `immutabook`이라 이름짓는다.
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 ^ 해당 라인을 주석처리 하세요.
}