Why can't I borrow vector content in a box as mutable?

Why this does not compile:

fn main() {
    let mut b = Box::new(Vec::new());
    b.push(Vec::new());
    b.get_mut(0).unwrap().push(1);
}

While doing this:

fn main() {
    let a = Box::new(Vec::new());
    let mut b = *a;
    b.push(Vec::new());
    b.get_mut(0).unwrap().push(1);
}

And also it does:

fn main() {
    let mut b = Vec::new();
    b.push(Vec::new());
    b.get_mut(0).unwrap().push(Vec::new());
    b.get_mut(0).unwrap().get_mut(0).unwrap().push(1)
}

The first and third for me are conceptually the same - Vector box of vectors vectors and vector vectors vectors vectors. But the latter leads to the fact that each vector is mutable, while the first makes the inner vector unchanged.

+4
source share
1 answer

You need to undo your value before accessing it as mutable:

fn main() {
    let mut b = Box::new(Vec::new());
    b.push(Vec::new());
    (*b).get_mut(0).unwrap().push(1);
}

This is because the statement .uses Dereftrait instead DerefMut.

EDIT:

The best way to achieve this:

fn main() {
    let mut b = Box::new(Vec::new());
    b.push(Vec::new());
    b[0].push(1);
}
0
source

All Articles