通常,拥有者是变量或字段;它们负责释放所拥有的值。但更令人惊讶的是,甚至程序二进制文件也可以成为拥有者。例如,字符串字面量就是这种情况:
let s = "Hello World";
上面的字符串字面值存储在程序二进制文件中,s
只是对它的引用。因此,它的生命周期是'static'
,即字面值的寿命与程序执行相对应。
正如其他人所说,所有者是变量或字段。
我想举一个实际的例子:
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