Reputation: 107
I want to keep only the first 2 elements in a Vec
and release any unused capacity. Here is my current solution:
let mut data = vec![1, 2, 3, 4, 5, 6]; // produced by another function
data.truncate(2);
data.shrink_to_fit();
Is there a better way to do this?
Upvotes: 2
Views: 1103
Reputation: 34987
Rust docs https://static.rust-lang.org/doc/master/std/vec/struct.Vec.html#guarantees
In general, Vec's allocation details are subtle enough that it is strongly recommended that you only free memory allocated by a Vec by creating a new Vec and dropping it.
I'm a Rust noob, but it seems to say that the solution would be:
let v = vec![v[0], v[1]];
(or vec![&v[0], &v[1]]
if appropriate);
BTW. https://static.rust-lang.org/doc/master/std/vec/struct.Vec.html#guarantees also says:
push
andinsert
will never (re)allocate if the reported capacity is sufficient.push
andinsert
will (re)allocate iflen()==capacity()
. That is, the reported capacity is completely accurate, and can be relied on. It can even be used to manually free the memory allocated by aVec
if desired.
I don't understand how to use this information :)
Upvotes: 1
Reputation: 361605
Truncating and shrinking is the best way. Releasing unused capacity is a distinct operation; there's no way around it. Rust doesn't do it automatically since you might be removing and then adding more elements.
Upvotes: 2