While references can have lifetimes, types can have lifetimes too. The simplest example would probably be:
struct Foo<'a> {
x: &'a i32
}
If you construct a struct of type Foo
(let's call this instance foo
) with a reference to an i32
(let's call this num
) on the local stack, then foo
cannot live longer than the scope of num
, regardless of the scope of foo
itself. It's a lifetime without a reference (to the type, at least).
Let's take a look at a real world example of this: Box::leak
:
pub fn leak<'a>(b: Box<T>) -> &'a mut T
where
T: 'a,
The type signature basically says that, given a box, you can create a reference to its value for any lifetime as long as the value itself is capable of lasting for that lifetime. So, we could create a &'static i32
with Box::leak
, since i32
has nothing restricting its lifetime, but we can't create a &'static Foo
that references a stack integer, as it has a reference restricting its lifetime.
Note that if you're testing this locally, things like &5
will actually create a &'static i32
due to rvalue static promotion, so you might want to change the i32
to an unpromotable type like String
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…