简体   繁体   中英

How do I declare the lifetime parameters for a type which contains a reference to a type with a lifetime parameter?

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:

  1. The lifetime of the reference to foo should be the lifetime of the Bar containing it
  2. 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

edit : 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM