Reputation: 3307
Trying to figure out how to describe this lifetime relationship.
So let's say I have a component which has a lifetime parameter:
struct Foo<'a> { ... }
And let's say I want to have another component which contains a reference to Foo
struct Bar<??> {
foo: &'? Foo<'?>
}
How do I express the following:
foo
should be the lifetime of the Bar
containing itFoo
, so long as it's longer than the lifetime of the Bar
containing the referenceedit: So if Foo
itself didn't have a lifetime parameter, I would implement Bar
like this:
struct Bar<'a> {
foo: &'a Foo
}
But I don't know how to handle the parameter on Foo
.
Upvotes: 0
Views: 347
Reputation: 732
I don't care about the lifetime of the underlying Foo, so long as it's longer than the lifetime of the Bar containing the reference
First, the lifetime can be read like "this element lives at least 'x", so when you declaring struct Foo<'a> { ... }
means a X instance of Foo lives at least 'a, where 'a is a variable like any other variable, but is a lifetime variable.
Now,
How do I express the following:
The lifetime of the reference to foo should be the lifetime of the Bar containing it
To express this you need declare the lifetime variable for Bar
and pass it to Foo
like this
struct Bar<'a> {
foo: &'a Foo<'a>
}
or
struct Bar<'a> {
foo: Foo<'a>
}
The difference between one and the other is semantic, and means that one contains an element of type Foo<'a>
and the other contains a reference to an element of type Foo<'a>
.
Now,
I don't care about the lifetime of the underlying Foo, so long as it's longer than the lifetime of the Bar containing the reference
Passing a lifetime 'down' necessarily implies that the children element lives at least as long as its parent, but not necessarily that it lives longer. To express that regardless of the parent's lifetime the child lives in a major scope you would need to use a 'static' lifetime. Like this
struct Bar {
foo: &'static Foo<'static>
}
or
struct Bar {
foo: Foo<'static>
}
also you can make some like this
struct Bar<'a> {
foo: &'a Foo<'static>
}
which means that the reference to the element lives as long as the parent but the element itself has a wider scope
I don't know if this answers your question, I hope it helps
Upvotes: 1