我明白借用不能比它所指向的事物的存在时间更长,以消除悬空指针。
借用或别名可以通过伪造生命周期比所有者长寿:
fn main() {
let e;
let first = "abcd";
{
let second = "defgh";
e = longest(first, second);
}
println!("{}", e);
}
fn longest<'a>(first: &'a str, second: &'a str) -> &'a str {
if first.len() > second.len() {
first
} else {
second
}
}
结果:
defgh
在上面的例子中,变量 e
比 second
变量有更长的生命周期,显然 first
& second
变量的生命周期不同。
当 e
用 longest(first, second)
初始化时,它得到 second
变量,其函数调用的生命周期是伪造的等于 first
但它被限制在 block 中并且它被分配给 e
这将超过 second
。为什么这样可以?
最佳答案
这是因为它们都具有 'static
生命周期。
这是一个不起作用的例子,因为这里的 str
不像 &'static str
那样在程序的生命周期中存在。
唯一的变化是以下行:let second = String::from("defgh");
以及传递给 longest 函数的下一行。
fn main() {
let e;
let first = "abcd";
{
let second = String::from("defgh");
e = longest(first, &second);
}
println!("{}", e);
}
fn longest<'a>(first: &'a str, second: &'a str) -> &'a str {
if first.len() > second.len() {
first
} else {
second
}
}
这是错误:
error[E0597]: `second` does not live long enough
--> src/main.rs:6:28
|
6 | e = longest(first, &second);
| ^^^^^^^ borrowed value does not live long enough
7 | }
| - `second` dropped here while still borrowed
8 | println!("{}", e);
| - borrow later used here
更多信息可以在 Static - Rust By Example 中找到
关于rust - 为什么借用的字符串字面量可以通过伪造生命周期比其所有者长寿?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54115451/