3 ms·
In the case of a Vec<Box<T>> the Vec owns the box, so the only thing you could link the reference lifetime to is the Vec itself because if the lifetime isn't bo
by Measter 5y ago
In the case of a Vec<Box<T>> the Vec owns the box, so the only thing you could link the reference lifetime to is the Vec itself because if the lifetime isn't bound to the Vec, mutating the Vec might drop that item which in the case of Box<T> will also deallocate the memory. If any references point directly to that memory, then it would be dangling.
In the case of Rc<T>, cloning the Rc creates a second owner of the heap allocation, so the Vec dropping its copy won't deallocate. Though I believe one complication to this would be that the lifetime any references created through the Vec's copy of the Rc will be linked specifically to that copy, so would result in a borrow check error when it's dropped.
If the Vec is storing references, you can borrow the thing behind the reference and still mutate the Vec because that reference stays valid even if mutating the Vec drops its reference to the item.
let (a, b, c, d) = (1, 2, 3, 4);
let mut v = vec![&a, &b, &c, &d];
// If you change the type here to &&u32, or let the compiler infer the type
// then you'll get a borrow check error because the outer reference
// borrows the Vec.
let borrowed_b: &u32 = &v[1];
v.remove(1);
println!("{}", borrowed_b);
println!("{:?}", v);
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7762c73cf306917e28aaec2de8c4e131 https://play.rust-lang.org/?version=stable&mode=debug&editio...
[1]