星期六, 10月 21, 2023

Rust 的基礎- 所有權規則

 Rust 中

  1. 每個 Value 都有 "所有者"
  2. 在任意時刻只會有一個 "所有者"
  3. 當所有者離開其所在範圍時,Value 會被 Drop

第一條規則

let hello = "Hello World".to_string()

此範例 "Hello World" 是 Value, 所有者是 hello

 

第二條規則

let hello2 = hello;

此範例中 hello 所擁有的 "Hello World" 被轉移(Move) 給 hello2.

此時若在使用 hello, 則會編譯錯誤

16 |    let hell2 = hello;
   |                ----- value moved here
17 |    println!("{}", hello);
   |                   ^^^^^ value borrowed here after move


第三條規則

let hello = "Hello World".to_string()
{
    let hello2 = hello;
    // <-- 在離開 Scope 後, "Hello World" String 就被 Drop 了
}

從以上的三條規則來看,這些規則可能可以防範

  1. Dangling Pointer (由於一次只有一個 Owner, 被 Move 就失效因此無法再存取)
  2. Use After Free (由於一次只有一個 Owner, 被 Move 就失效因此無法再存取)
  3. Memory Leak (Circular 會有狀況)

沒有留言: