mirror of
https://github.com/ahgamut/rust-ape-example.git
synced 2024-05-16 02:22:41 +00:00
54 lines
1.3 KiB
Rust
54 lines
1.3 KiB
Rust
// ./src/scope/borrow/mut.md
|
|
|
|
|
|
#[allow(dead_code)]
|
|
#[derive(Clone, Copy)]
|
|
struct Book {
|
|
// `&'static str` is a reference to a string allocated in read only memory
|
|
author: &'static str,
|
|
title: &'static str,
|
|
year: u32,
|
|
}
|
|
|
|
// This function takes a reference to a book
|
|
fn borrow_book(book: &Book) {
|
|
println!("I immutably borrowed {} - {} edition", book.title, book.year);
|
|
}
|
|
|
|
// This function takes a reference to a mutable book and changes `year` to 2014
|
|
fn new_edition(book: &mut Book) {
|
|
book.year = 2014;
|
|
println!("I mutably borrowed {} - {} edition", book.title, book.year);
|
|
}
|
|
|
|
fn part0() {
|
|
// Create an immutable Book named `immutabook`
|
|
let immutabook = Book {
|
|
// string literals have type `&'static str`
|
|
author: "Douglas Hofstadter",
|
|
title: "Gödel, Escher, Bach",
|
|
year: 1979,
|
|
};
|
|
|
|
// Create a mutable copy of `immutabook` and call it `mutabook`
|
|
let mut mutabook = immutabook;
|
|
|
|
// Immutably borrow an immutable object
|
|
borrow_book(&immutabook);
|
|
|
|
// Immutably borrow a mutable object
|
|
borrow_book(&mutabook);
|
|
|
|
// Borrow a mutable object as mutable
|
|
new_edition(&mut mutabook);
|
|
|
|
// Error! Cannot borrow an immutable object as mutable
|
|
// new_edition(&mut immutabook);
|
|
// FIXME ^ Comment out this line
|
|
}
|
|
|
|
pub fn main() {
|
|
part0();
|
|
}
|
|
|