2015-02-07 38 views
4

为什么这并不编译:为什么我不能借用盒装的矢量内容作为可变?

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

第一和第三个对我来说是概念上的相同 - Ints矢量矢量盒和Ints矢量矢量盒。但最后一个导致每个向量都是可变的,而第一个导致内部向量不可变。

回答

0

你需要拆箱你的价值,访问它作为一个可变前:

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); 
} 
+1

对不起,我的英语,但我过量咖啡因,这是很难集中。 – Hauleth 2015-02-07 19:35:49

+0

如果'.'运算符只使用'Deref',那么为什么'b.push(Vec :: new())'工作?这需要一个可变的接收器,不是吗? – Shepmaster 2015-02-07 19:41:01

+0

我不知道,现在想我已经太迟了。但'get_mut'将会被赞成使用'IndexMut'。相反,你可以使用'b [0] .push(1)',它可以正常工作。我明天可以为你调查。 – Hauleth 2015-02-07 19:51:51

相关问题