You cannot currently put the two in lines into one as described in Cannot borrow as immutable because it is also borrowed as mutable in function arguments.
but I'm pretty sure that there is an one-liner...
Of course:
{ let old_size = my_vec.len(); my_vec.resize(old_size - 2, 0x00); }
Less cheekily, you can add a trait method:
trait ResizeRelative<T> {
fn resize_relative(&mut self, delta: isize, default: T);
}
impl<T: Clone> ResizeRelative<T> for Vec<T> {
fn resize_relative(&mut self, delta: isize, default: T) {
let len = if delta < 0 {
self.len() - ((-delta) as usize)
} else {
self.len() + delta as usize
};
self.resize(len, default);
}
}
fn main() {
let mut v = Vec::new();
v.resize_relative(3, 42);
v.resize_relative(-1, 2);
println!("{:?}", v);
}
Note the gyrations you need to perform to be able to resize in both directions. Even then, there's still the possibility of panicking if you resize below zero.