为什么我不能借用盒装矢量内容作为可变内容?

Why can I not borrow a boxed vector content as mutable?

为什么不能编译:

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

同时这样做:

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

这也是:

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)
}

第一个和第三个对我来说在概念上是相同的 - Box 一个 Vector 的 Vector 的整数和一个 Vector 的 Vector of Vectors of integers,但最后一个导致每个向量可变,而第一个使内部向量不可变。

您需要先拆箱您的值,然后才能将其作为可变值访问:

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

这是因为 . 运算符使用 Deref 特征而不是 DerefMut

实现此目标的最佳方法是:

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

至少在 Rust 1.25.0 中,所有三个原始示例都有效。这是 Rust 以前版本中的一个错误。