1

If I want to resize a vector in C++/Swift/Any other language I usually write something like this my_vec.resize(my_vec.size(), 0x00); but if I try this in Rust I get the error immutable borrow occurs here.

Of course I can write something like this:

let old_size = my_vec.len();
my_vec.resize(old_size - 2, 0x00);

but I'm pretty sure that there is an one-liner...

K. Biermann
  • 1,295
  • 10
  • 22
  • Very similar question: https://stackoverflow.com/questions/41352710/nested-method-calls-with-mut-receivers-result-in-borrow-checker-errors – fghj Aug 02 '17 at 16:56
  • 1
    There is rfc about it: https://github.com/rust-lang/rfcs/issues/811 it would be interesting to know progress on this. – fghj Aug 02 '17 at 16:56
  • Is this only to truncate a vector, or are you looking for a solution that can also grow it? – 8bittree Aug 02 '17 at 16:57
  • Im looking for a solution to generally resize a vector. – K. Biermann Aug 02 '17 at 17:00

1 Answers1

3

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    Ah, now I understand the problem... I thought the function was evaluated after the function-parameters; I didn’t realize that the function really got expanded to `Vec::resize(&mut my_vec, ...)` – K. Biermann Aug 02 '17 at 17:18