This was discussed at IRC yesterday, which left me vaguely unhappy.
The question was:
How do you determine the life expectancy in a structure in order to limit its contents only to those things that live as long as "yourself."
i.e. "in itself".
My initial reaction was: you cannot.
If you create a structure Foo <'a>, the lifetime associated with it is inferred from the links it contains; if the structure does not contain a reference to itself (impossible), you cannot have such a “own lifetime”.
There was a lot of chatter in this, and in the end I wrote this playpen :
struct Bar;
struct Foo<'a> {
a:&'a Bar,
b:&'a Bar
}
fn factory<'a>(v1:&'a Bar, v2: &'a Bar) -> Foo<'a> {
return Foo {
a: v1,
b: v2
};
}
fn main() { // <---- Let call this block lifetime 'one
let a = Bar;
let c = &a; // <-- C has lifetime 'one
{ // <------------ Let call this block lifetime 'two
let b = Bar;
let mut foo1 = factory(c, c);
foo1.b = &b;
let mut foo2 = factory(&b, &b);
foo2.a = &a;
println!("{}", foo1);
println!("{}", foo2);
}
}
However, now I am more confused than less.
So, in the strict sense of the above:
- c has one
- & b '
- 'static > ' one > 'two (.. ).
- foo1 ""
- foo2 'two
, :
Foo < 'a > , ' a - , Foo.
'one > ' two, foo2 a & 'one a; .
'two > ' one, foo1 & 'two b; .
?
, ; :
1) foo1 Foo < 'two > , Foo <' one > .
, , factory < 'a > , <' a > - c; ", ". , c & 'two . ' factory, Foo.
2) Structures , ; . 'a Foo - (, ?)
... , .