Two questions about the "Reference lifetime" chapter of the offcial tutorial

I think it may help to be more precise with terminology here.

Rust values do not have (what Rust calls) lifetimes -- as in, those '_ things. They do have liveness scopes, but where values drop is (mostly) a dynamic property, where as lifetimes are a compile time construct.

Some (but not all) types are what have lifetimes.

References to values cannot have a type with a lifetime longer than the liveness scope of the value. That's the main connection between liveness scopes and lifetimes.

Values also don't directly participate in lifetime bounds (e.g. T: 'static). Lifetime bounds check the properties of types, not values.

Most types satisfy a static bound. That doesn't mean values with that type never drop.


A lot of learning material and even official documentation is fast and loose with their terminology, and will use the term "lifetime" to mean the liveness of values without distinguishing that from Rust lifetimes ('_). Rust by example is apparently one of those.

(It was arguably a misstep to use the common term "lifetime" for those '_ things.)


The closest thing to values having a (Rust) lifetime is probably static values. These values last for the entire run of your program, and are shared and accessible by all threads. The type has to meet a static bound, and you can create a &'static _ to them.

They still don't have actually have a '_ lifetime though.

statics never drop. They're stored in your executable, not on the stack (or in a register), in contrast with local variables.

You can never have a &'static _ to a local variable, because of the variables scope - it necessarily drops or gets moved by the time the function ends.


Ok, to your questions finally.

The example would be more accurate like so.

// Returns a reference to `NUM` where its `'static`
// lifetime is coerced to that of the input argument.
fn coerce_static<'a>(_: &'a i32) -> &'a i32 {
    let static_num_ref = &'static Num;
    &static_num_ref
}

It's the reference type that has a lifetime, not NUM. NUM wasn't coerced, the reference was. (Without the annotation, like in the original, it didn't necessarily have a 'static lifetime or need coerced at all.)

Nothing happened to the NUM value.

The NUM value doesn't have a lifetime. Taking references to it doesn't change the fact that it lasts for the entire run of your program.

Equality in Rust generally follows references. This isn't a pointer comparison, it's comparing the randomly generated contents. There's a (very small) chance they'll be equal.

Not sure why they have the assertion.

I think they're trying to show that Rust lifetimes only matter from the time they're created forward. This is true of all lifetimes, not just 'static. So a &'static _ can be created which points to a value that was dynamically created (provided it leaks), even though said value did not exist when the program started.

3 Likes