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 ^ .
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

See also:

static

results matching ""

    No results matching ""