iT邦幫忙

2023 iThome 鐵人賽

DAY 16
0

昨天懵懵懂懂的說明了 Rust 的所有權 move 概念,

今天要來看 borrow 啦!

我們一樣來看例子

所有權概念 - borrow

假設有一間店叫做 shop1

fn main() {
    let shop1 = ["milk", "tea", "coffee"];
}

今天 shop2 要開了,而且是全台旗艦店,不過因為太緊急沒有產品,需要跟 shop1 「借用」

& 在 Rust 中代表借用的意思

這邊代表的意思是, shop1 將他的產品借給 shop2 販售,

不過所有權還是在 shop1 上

fn main() {
    let shop1 = ["milk", "tea", "coffee"];

    let shop2 = &shop1;

    println!("{:?}", shop1);
    println!("{:?}", shop2);
}

讓我們來看看記憶體是怎麼分配的

用「borrow」的方式,兩個變數都會指向同一個記憶體位址

但因為所有權仍然在 shop1 身上,就算今天 shop2 出了 scope

value 仍然還是在,除非 shop1 出了 scope

我們來看看他們的記憶體位置,都是指向相同的位址

fn main() {
    let shop1 = ["milk", "tea", "coffee"];
    let shop2 = &shop1;

    let ptr = shop1.as_ptr();
    let ptr2 = shop2.as_ptr();

    println!("shop1's value is pointed to {:?}", ptr);
    println!("shop2's value is pointed to {:?}", ptr2)
}
> cargo run

shop1's value is pointed to 0x16b67a228
shop2's value is pointed to 0x16b67a228

再來我們將 shop2 包進一個 scope 中,並且借用 shop1 的值

fn main() {
    let shop1 = ["milk", "tea", "coffee"];

    {
        let shop2 = &shop1;
        println!("in scope, shop2 has {:?}", shop2);
    }
}
> cargo run

in scope, shop2 has ["milk", "tea", "coffee"]

如果離開 scope 之後呢? shop1 的值還存在

fn main() {
    let shop1 = ["milk", "tea", "coffee"];

    {
        let shop2 = &shop1;
        println!("in scope, shop2 has {:?}", shop2);
    }

    println!("{:?}", shop1);
}
> cargo run

in scope, shop2 has ["milk", "tea", "coffee"]
["milk", "tea", "coffee"]

一樣可以來看看他們的記憶體位址,也都是指向同一個位址

出了 scope , shop1 的值依然存在

fn main() {
    let shop1 = ["milk", "tea", "coffee"];

    {
        let shop2 = &shop1;
        let ptr2 = shop2.as_ptr();
        println!("shop2's value is pointed to {:?}", ptr2)
    }

    let ptr = shop1.as_ptr();
    println!("shop1's value is pointed to {:?}", ptr);
}

> cargo run

shop2's value is pointed to 0x16db26228
shop1's value is pointed to 0x16db26228

上一篇
Day 15 Ownership part 1
下一篇
Day 17 Ownership part 3
系列文
成為程式界的 F1 賽車手,用 30 天認識 Rust 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言