为什么通用生命周期不符合嵌套作用域的更小生命周期?

10
根据Rust编程语言的说法:
由于作用域总是嵌套的,因此另一种表达方式是通用生命周期'a将获得等于xy寿命较小者的具体寿命。
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
    }
}

在主函数中,“x和y寿命较短的那个”是嵌套作用域。这也应该是result中值的寿命,但结果包含了来自嵌套作用域之外的正确值。
为什么这段代码能正常工作?
1个回答

7

只有在讨论从本地变量借用得出的生命周期时才是真实的。在这种情况下,相关的生命周期是字符串数据的生命周期,对于字符串字面值而言是'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

这个失败是因为现在我们谈论的是借用到栈中的内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接