What is the lifetime of a const variable?

In this reply, I'm using the distinction between lifetimes ('_) and value liveness I outlined in your other topic.

Applying the distinction to the tutorial page: the static value doesn't have a lifetime, but it lasts "forever" (the run of your program). It's liveness scope is "forever". If the type of a static happens to have lifetimes, those lifetimes must be 'static.

Let's talk about Rust lifetimes ('_) first.

If the type of a const declared at the top level has lifetimes, those lifetimes are 'static. There's no other named lifetimes it could be, after all. However, you can also declare consts in other places, like associated constants of types. In those contexts, a 'static default for elided lifetimes doesn't apply, and there are may be other possible named lifetimes available (if the type or any traits involved have lifetime parameters).

Additionally, there was an accidental stabilization of allowing elided lifetimes in associated consts to be inferred at the use site (which is more general than being 'static, and thus more general than top-level consts). For now, eliding explicit lifetimes in a context other than the top level generates a warning. Some day it may once again be an error.

Examples. (And some invariance/inferred examples.)

...so any lifetimes in the types of a const declared at the top level are 'static, in associated consts they may or may not be 'static, or it might even be inferred at the use site and not enforced at the declaration site (for now).


Now let's talk about liveness scopes.

A const acts as-if if you pasted the definition everywhere you use the const value. So the liveness scope is going to depend on how you use the value. If the type of the const satisfies a 'static bound, you could perhaps[1] assign it to a static and the value will last forever. Or you could assign it to a local variable, and the liveness of that value will act like any other local variable.

@drewtato mentioned constant promotion -- if you use the const in such a way that the compiler decides it should use constant promotion to make the value a static value, naturally the value will last forever (and any lifetimes of the type will necessarily be 'static).


  1. static types must also be Sync, but const types don't have to be -- since there is no global value at the declaration site ↩︎