Const and static lifetimes

I'm pretty sure I read somewhere that the lifetime of all const and static values is 'static which is the duration of the program. I understand that const values are just substituted everywhere they are referenced by the compiler. So what's the significance of saying the lifetime of a const that is defined inside a function, and therefore only substituted into references in that function, is 'static? Is it just that because of the way const values are substituted into references by the compiler, they effectively never go out of scope because they don't really exist in the running program? It seems like the term "lifetime" doesn't really apply to const values.

1 Like

Your understanding is correct: const doesn't create a value with a scope of its own, so it doesn't really make sense to talk about its “lifetime.”

However, a const may contain a 'static reference, for example:

const A: &'static [i32] = &[1, 2, 3];
const B: &'static str = "Hello";

These declarations implicitly create a static value, and then create a const reference to that value. This might be what someone is talking about if they refer to a const with a 'static lifetime.


You can also take a reference to a const value, and the reference will have the 'static lifetime.

1 Like

To expand on what @quinedot is saying there, it's essentially the same as what @mbrubeck was referring to, just without naming the reference as a const:

const X: usize = 0;

let foo: &'static usize = &X;

// Same idea as

let bar: &'static usize = &10;

And, in a sense, this applies to string literals:

const STR_DATA: [u8; 3] = [b'f', b'o', b'o'];
let my_weird_str: &'static [u8; 3] = &STR_DATA;

// Same idea as

let my_regular_str = "foo";