什么可以成为所有者?

4

Rust书中指出:

Rust中的每个值都有一个所有者

它没有解释这个所有者是哪种类型的实体。是程序员吗?变量?语句?代码块?

那么,什么样的实体可以成为“值所有者”的准确定义是什么?


2
这是一个变量或字段。基本上,需要有一些“东西”,以便如果该“东西”超出范围,您可以确定变量可以安全地删除。 - mousetail
2个回答

1

通常,拥有者是变量或字段;它们负责释放所拥有的值。但更令人惊讶的是,甚至程序二进制文件也可以成为拥有者。例如,字符串字面量就是这种情况:

let s = "Hello World";

上面的字符串字面值存储在程序二进制文件中,s只是对它的引用。因此,它的生命周期是'static',即字面值的寿命与程序执行相对应。


1

正如其他人所说,所有者是变量或字段。

我想举一个实际的例子:

fn main() {
    // s is the owner of the string.
    let s: String = String::from("Hello!");

    // r is the owner of the reference, which in turn references s.
    // It can access the string, but does not own it.
    let r: &String = &s;

    // That means if we drop `s`, which owns the string, the string gets destroyed.
    drop(s);

    // Meaning `r` is now also forced to be dropped, because it does not own the
    // string, and would now be a dangling reference. The borrow checker prevents
    // dangling references, so this is a compilation error.
    println!("{}", r);
}

error[E0505]: cannot move out of `s` because it is borrowed
  --> src/main.rs:10:10
   |
7  |     let r: &String = &s;
   |                      -- borrow of `s` occurs here
...
10 |     drop(s);
   |          ^ move out of `s` occurs here
...
15 |     println!("{}", r);
   |                    - borrow later used here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接