什么可以成为所有者?

huangapple go评论47阅读模式
英文:

What can be an owner?

问题

Rust book 中指出:
> Rust 中的每个值都有一个 所有者

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

"值所有者" 可以是什么类型的实体的确切定义是什么?

英文:

The Rust book states:
>Each value in Rust has an owner

It does not explain what type of entity this owner is. Is it a programmer? a variable? A statement? A code block?

What is the precise definition of what type of entity can be a 'value owner'?

答案1

得分: 1

通常,所有者是变量或字段;它们负责释放所拥有的值。然而,更令人惊讶的是,甚至程序二进制代码也可以是一个所有者。例如,这对于字符串字面值来说就是这种情况:

let s = "Hello World";

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

英文:

Usually, owners are variables or fields; they are responsible for dropping the value owned. However, more surprisingly, even the program binary can be an owner too. As an example, that's the case for string literals:

let s = "Hello World";

The string literal above is stored in the program binary itself, s is just a reference to it. As such, its lifetime is 'static, i.e., the literal lifespan corresponds to the program execution.

答案2

得分: 1

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

我只想添加一个实际示例:

fn main() {
    // s 拥有这个字符串。
    let s: String = String::from("Hello!");

    // r 拥有引用,该引用又引用了 s。
    // 它可以访问字符串,但不拥有它。
    let r: &String = &s;

    // 这意味着如果我们放弃 `s`,它拥有字符串,字符串将被销毁。
    drop(s);

    // 这意味着 `r` 现在也被强制放弃,因为它不拥有字符串,现在它会成为悬空引用。
    借用检查器会阻止悬空引用,因此这会导致编译错误。
    println!("{}", r);
}
error[E0505]: 无法从 `s` 中移出,因为它被借用
  --> src/main.rs:10:10
   |
7  |     let r: &String = &s;
   |                      -- 在这里对 `s` 进行了借用
...
10 |     drop(s);
   |          ^ 在这里发生了 `s` 的移出
...
15 |     println!("{}", r);
   |                    - 后来在这里使用了借用
英文:

As other people stated, owners are variables or fields.

I just wanted to add a practical example:

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

huangapple
  • 本文由 发表于 2023年2月8日 17:04:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定