I see why I need to use life times in this code, I have noted it in the comments. But I cannot find a syntax for them that will work.
struct Foo {
x: usize,
}
impl Foo {
// [a] Using `Self` here. Could use `Foo`. Is it the same thing
// in this context
fn new(i:usize, holder: &mut Vec<& Self>) -> Self{
// Creating a `Foo` object, placing a reference to it in
// `holder`. The reference, and Foo, need to live as long as
// `holder`
let ret = Foo {
x:i,
};
holder.push(&ret);
ret
}
}
fn main() {
// This is the scope where all the data must live. How?
let mut held:Vec<&Foo> = Vec::new();
for i in 0..10 {
// This `Foo` objects need to live as long as the `held` vec
Foo::new(i, &mut held);
}
// Do something with `held`
}
I know this is weird code. It is a small part of a larger project. I extracted the part that illustrates what I cannot make work.
I have not included all the different things I tried. I find myself thrashing around and nothing compiles.
The compiler says....
cargo build
Compiling lifetimes v0.1.0 (/home/patch/sandbox/lifetimes)
error[E0597]: `ret` does not live long enough
--> src/main.rs:16:14
|
9 | fn new(i:usize, holder: &mut Vec<& Self>) -> Self{
| - let's call the lifetime of this reference `'1`
...
16 | holder.push(&ret);
| ------------^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `ret` is borrowed for `'1`
17 | ret
18 | }
| - `ret` dropped here while still borrowed
error[E0505]: cannot move out of `ret` because it is borrowed
--> src/main.rs:17:2
|
9 | fn new(i:usize, holder: &mut Vec<& Self>) -> Self{
| - let's call the lifetime of this reference `'1`
...
16 | holder.push(&ret);
| -----------------
| | |
| | borrow of `ret` occurs here
| argument requires that `ret` is borrowed for `'1`
17 | ret
| ^^^ move out of `ret` occurs here
error: aborting due to 2 previous errors
It is telling me (I think) that the Foo
instance must live as long as the vector the reference is placed in. That I know. How do I tell the compiler?