scope - 为什么泛型生命周期不符合嵌套范围的较小生命周期?

标签 scope rust lifetime

根据 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 of x and 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
    }
}

在 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/

相关文章:

rust - 如何使用 Serde 的自定义(反)序列化来更新任意输入的子集?

rust - 如何以函数式方式在向量中查找值并返回其索引?

c++ - 使用 const 引用延长临时对象的生命周期

rust - 盒装结构包含引用时的降序

Javascript 闭包/可变范围问题 - 我知道它有效,但为什么呢?

JavaScript 范围解析时间

rust - (Rust) 有没有办法为重载的运算符自动借用?

javascript - 如何制作返回其内部函数值的函数?

c# - 继承 ThreadStatic 值以在多线程上下文中的 C#/.NET 中实现动态作用域

reference - 如何为对结构的引用实现 Add 特性?