sag*_*aga 9 scope lifetime rust
根据Rust编程语言:
由于示波器总是窝,另一种说法.这是一个通用的寿命
'a将得到具体的寿命相等的寿命的小x和y.
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
}
}
Run Code Online (Sandbox Code Playgroud)
在main函数中,"x和y的生命周期中较小的"是嵌套范围.这也应该是值的生命周期result,但结果包含来自该嵌套范围外部的正确值.
为什么这段代码正常工作?
在谈论借用局部变量所产生的生命期时,这是唯一的.在这种情况下,相关生命周期是字符串数据的生命周期,对于字符串文字是'static.换句话说,&strs指向存储在别处的数据(特别是在静态数据段中),因此它们根本不与堆栈生存期交互.
如果我们稍微更改示例,我们可以诱导您期望的行为:
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
}
}
Run Code Online (Sandbox Code Playgroud)
哪个无法编译:
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
Run Code Online (Sandbox Code Playgroud)
这失败了,因为现在我们正在谈论借入堆栈.