根据 The Rust Programming Language :
Since scopes always nest, another way to say this is that the generic lifetime
'a
will get the concrete lifetime equal to the smaller of the lifetimes ofx
andy
.
fn main() {
let x = "abcd";
let result;
{
let y = "qwerty";
result = longest(x, y);
}
println!("The longest string is {} ", result);
}
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
在 main 函数中,“x 和 y 的生命周期中较小的一个”是嵌套作用域。这也应该是 result
中值的生命周期,但结果包含来自该嵌套范围之外的正确值。
为什么这段代码可以正常工作?
最佳答案
只有在谈论通过借用局部变量派生的生命周期时才是正确的。在这种情况下,相关的生命周期是字符串数据的生命周期,对于字符串文字来说是'static
。换句话说,&str
指向存储在别处的数据(特别是在静态数据段中),因此它们根本不与堆栈生命周期交互。
如果我们稍微改变一下示例,我们可以诱发您期望的行为:
fn main() {
let x = "abcd";
let result;
{
let y = "qwerty";
result = longest(&x, &y);
}
println!("The longest string is {} ", result);
}
fn longest<'a>(x: &'a &'static str, y: &'a &'static str) -> &'a &'static str {
if x.len() > y.len() {
x
} else {
y
}
}
编译失败:
error[E0597]: `y` does not live long enough
--> src/main.rs:6:35
|
6 | result = longest(&x, &y);
| ^ borrowed value does not live long enough
7 | }
| - `y` dropped here while still borrowed
...
10 | }
| - borrowed value needs to live until here
这失败了,因为现在我们正在讨论向堆栈借用。
关于scope - 为什么泛型生命周期不符合嵌套范围的较小生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49292404/