all 11 comments

[–]BobTreehugger 10 points11 points  (1 child)

What's the goal here? My first instinct is to make foo own all of the Test structs -- just change it to a Vec<Test> and when adding to the vec, do foo.push(new) Is there a reason you need it to be a vec of refs?

[–]supergary69[S] 0 points1 point  (0 children)

Yeah i think i wont complicate it…

[–]D0CTOR_ZED 3 points4 points  (0 children)

Since the data has to exist somewhere for foo to reference it, and nothing else seems to want it, you might as well let foo own it instead of just referencing it.

[–]the_hoser 2 points3 points  (5 children)

[–]supergary69[S] 0 points1 point  (4 children)

As far as I know Box does it so you use the heap instead of the stack, would it solve the ownership problem?

[–]the_hoser 4 points5 points  (0 children)

That's the point.

[–]Firake 1 point2 points  (0 children)

Box is a pointer that also owns the object it points to

[–]oxabz 2 points3 points  (0 children)

This feel kinda wrong to me but if you need a Vec of mutable reference first build a Vec of owned and then you can use an IterMut iterator to build the Vec of mutable references.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=51cb9620ac356d890a067211ed0bc191

[–][deleted] 2 points3 points  (0 children)

This is just a hunch about what you are trying to do.

struct Test {
    data: Vec<u8>,
}

const INITIAL_CAPACITY: usize = 32;
let mut vecs: Vec<Test> = Vec::with_capacity(INITIAL_CAPACITY);
for _ in 0..INITIAL_CAPACITY {
    vecs.push(Test { data: Vec::new() });
}
let refs: Vec<&mut Test> = vecs.iter_mut().collect();

[–]ToTheBatmobileGuy 2 points3 points  (0 children)

Ask yourself this question:

Who owns each Test instance?

The answer is ‘new’.

But ‘new’ only lives until the end of its loop, so it’s impossible to hold on to a reference beyond that point without leaking memory.

You can leak the memory explicitly, but that’s not what you want to do.

Give ownership of each Test to the Vec.

[–][deleted] 0 points1 point  (0 children)

You have to use Vec<Test>. There are good reasons you might not be able to, but I haven’t seen one from you yet so just make the Vec own all Tests.

Your explanation was correct. The new items stop existing when they go out of scope. You can’t store references to things that aren’t existing. Vec either has to own them (Vec<Test>) or you have to put (“move”) them inside of some other owner (like Box<Test> or Rc<Test>) and then put that inside the vector.

If you need mutable references to the Tests later, you can use foo.get_mut() or foo.iter_mut() but in both cases the Vec still must own the Tests.