I see statements like the following all over the internet. I think this is a misconception, which I found confusing, so I'm asking if I have this right.
Here's an example from a recent blog post:
struct SubstringMatch<'a> {
start: usize,
text: &'a str,
}
The compiler will force you to spell out the lifetimes, commonly
<'a>
by convention, which in this case dictates that the entireSubstringMatch
struct can only be alive as long as the&str
in the text field is.
I don't think it's true that Foo<'a>
means "the Foo
struct can only be alive as long as 'a
is". It's simply a statement that Foo
is generic on a lifetime called 'a
.
The explanation is confusing because it implies you could choose to write a struct that wasn't limited by its contained reference lifetimes, simply by not mentioning them in the <>
, which is impossible.
Structures inherently have to have a lifetime longer than any references they contain. It's not the contents of the <>
notation that makes that so. Of course, it's not incorrect to say that Foo<'a, 'b>
has to outlive 'a
and 'b
, but that's not because of the <'a, 'b>
itself, it's because of the references inside Foo
. It's a good rule of thumb for reading Foo<'a, 'b>
to notice that it must outlive 'a
and 'b
, but that's not what it means.
As a counterexample, I can put a &'static
in Foo
and not have to write Foo<'static>
(in fact that's invalid). But every Foo
's lifetime must nevertheless be 'static
.
I, at least, found the notation much easier to understand once I realized this, so I wanted to confirm this is accurate, and if so, ask people writing about Rust not to propagate this explanation. What do you think?