rust - 为什么借用的字符串字面量可以通过伪造生命周期比其所有者长寿?

标签 rust lifetime borrow-checker borrowing

我明白借用不能比它所指向的事物的存在时间更长,以消除悬空指针。

借用或别名可以通过伪造生命周期比所有者长寿:

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

在上面的例子中,变量 esecond 变量有更长的生命周期,显然 first & second 变量的生命周期不同。

elongest(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/

相关文章:

arrays - 通过函数修改结构的固定数组

rust - 在 Rust 中访问属性后调用 &mut self 上的方法

rust - 返回响应后,在后台运行长时间运行的异步函数

rust - 如何匹配所有空格?

struct - 尝试将自引用数据拆分为单独的结构

rust - 将 '&self' 方法中的闭包添加到结构中的属性

c++ - C++中类的静态数据成员和静态方法是静态对象吗?

rust - 如何返回指向拥有值 "does not live long enough"的指针?

rust - 如何使用堆引用惯用地构造结构?

rust - 发生移动是因为 `*arg` 的类型为 `String` ,该类型未实现 `Copy` 特征