1. 程式人生 > 其它 >【Rust】可變借用

【Rust】可變借用

環境

  • Rust 1.56.1
  • VSCode 1.61.2

概念

參考:https://doc.rust-lang.org/stable/rust-by-example/scope/borrow/mut.html

示例

main.rs

#[derive(Clone, Copy)]
struct Book {
    // `&'static str` 是隻讀記憶體的引用
    title: &'static str,
    year: u32,
}

fn borrow_book(book: &Book) {
    println!(
        "I immutably borrowed {} - {} edition",
        book.title, book.year
    );
}

// 可變借用
fn new_edition(book: &mut Book) {
    book.year = 2014;
    println!("I mutably borrowed {} - {} edition", book.title, book.year);
}

fn main() {
    let immutabook = Book {
        title: "Gödel, Escher, Bach",
        year: 1979,
    };

    // copy
    let mut mutabook = immutabook;
    // 不可變借用
    borrow_book(&immutabook);
    // 可變借用
    new_edition(&mut mutabook);

    // 編譯錯誤,不可變變數不能進行可變借用
    // new_edition(&mut immutabook);
}

總結

瞭解了 Rust 中的可變借用和不可變借用。

附錄