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

【Rust】借用

環境

  • Rust 1.56.1
  • VSCode 1.61.2

概念

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

示例

通過引用來傳遞物件,在 rust 中稱為借用。

main.rs

fn eat_box_i32(boxed_i32: Box<i32>) {
    println!("Destroying box that contains {}", boxed_i32);
}

fn borrow_i32(borrowed_i32: &i32) {
    println!("This int is: {}", borrowed_i32);
}

fn main() {
    // 堆上分配
    let boxed_i32 = Box::new(5_i32);
    // 自動解引用
    borrow_i32(&boxed_i32);
    {
        // 自動解引用
        let _ref_to_i32: &i32 = &boxed_i32;

        // 編譯錯誤,後面還有借用,不能取得所有權
        // eat_box_i32(boxed_i32);

        // 如果註釋掉這句,那麼前面的移動就是合法的
        borrow_i32(_ref_to_i32);
    }

    // 沒有任何引用和借用了,可以進行移動。
    eat_box_i32(boxed_i32);
}

總結

瞭解了 Rust 中的移動和借用,移動會取得所有權,而借用不會。

附錄