简体   繁体   中英

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

I'm trying to understand why the code below compiles. I wasn't expecting to be able to construct Wrapper<String> since T: 'static and runtime-allocated strings don't live for the entire lifetime of the program.

I think the reason this is allowed is because I'm setting T to a non-reference type ( String ). When I use a &str , or a struct containing a reference, the compiler issues the error I'd expect.

However, I haven't been able to find anything in the Rust docs that confirms my hypothesis, so maybe I don't fully understand the rules. Will all non-reference types satisfy the 'static lifetime bound on Wrapper<T> , or are there some that will fail?

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);
}

From the 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.

So I'd say the answer to your question is: yes, any type which has no references (or which only contains static references) satisfies the 'static bound.

Side note: according to that RFC, bounds like T: 'static and T: 'a are known as outlives requirements .

You can think of a type bound T: 'x as "Instances of T cannot suddenly become invalid because something that lives shorter than 'x was dropped.". However, this does not affect how long the instance of T itself lives.

So, a reference becomes invalid if the referenced thing is dropped. Which means that the referenced thing must live at least as long as 'x - for the entire run of the program in the case of 'static .

But something that own all its data - an i32 or a String for example - never becomes invalid because something else is dropped. An integer is good until it is dropped itself. So it satisfies the 'static bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM