非引用类型是否总是满足“静态”的生命周期?

Do non-reference types always satisfy a lifetime of 'static?

我想了解为什么下面的代码可以编译。我没想到能够构造 Wrapper<String>,因为 T: 'static 和运行时分配的字符串不会在程序的整个生命周期内都存在。

我认为这是允许的原因是因为我将 T 设置为非引用类型 (String)。当我使用 &str 或包含引用的结构时,编译器会发出我预期的错误。

但是,我还没有在 Rust 文档中找到任何可以证实我的假设的内容,所以我可能没有完全理解这些规则。是否所有非引用类型都满足 Wrapper<T> 上的 'static 生命周期限制,还是有一些会失败?

use rand::Rng;

struct Wrapper<T>
where
    T: 'static,
{
    value: T,
}

fn wrap_string() -> Wrapper<String> {
    // Use rng to avoid construcing string at compile time
    let mut rng = rand::thread_rng();
    let n: u8 = rng.gen();
    let text = format!("The number is {}", n);
    Wrapper { value: text }
}

fn main() {
    let wrapped = wrap_string();
    std::mem::drop(wrapped);
}

来自Background section of RFC 2093

[...] in order for a reference type &'a T to be "well formed" (valid), the compiler must know that the type T "outlives" the lifetime 'a -- meaning that all references contained in the type T must be valid for the lifetime 'a. So, for example, the type i32 outlives any lifetime, including 'static, since it has no references at all.

所以我会说你的问题的答案是:是的,任何没有引用(或只包含静态引用)的类型都满足 'static 限制。

旁注:根据该 RFC,T: 'staticT: 'a 等边界被称为 outlives requirements

您可以将类型绑定 T: 'x 视为 "Instances of T cannot suddenly become invalid because something that lives shorter than 'x was dropped."。但是,这不会影响 T 实例本身的寿命。

因此,如果引用的事物被删除,则引用将变得无效。这意味着引用的事物必须至少与 'x 一样长 - 对于 'static.

的整个 运行 程序

但是拥有所有数据的东西 - 例如 i32String - 永远不会因为其他东西被丢弃而变得无效。一个整数在它自己被丢弃之前是好的。所以它满足 'static 界限。