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