为什么Rust借用检查器拒绝此功能?

时间:2014-11-01 00:47:19

标签: rust

这个(非常愚蠢的)函数无法编译:

fn silliness(mut z: &mut int) {
    z = &mut *z;
}

编译器输出:

$ rustc blah.rs 
blah.rs:2:5: 2:16 error: cannot assign to `z` because it is borrowed
blah.rs:2     z = &mut *z;
              ^~~~~~~~~~~
blah.rs:2:14: 2:16 note: borrow of `z` occurs here
blah.rs:2     z = &mut *z;
                       ^~
error: aborting due to previous error

在我看来,因为在任何时候只有一个参考z指向的内容,所以事情应该没问题。我不明白的是什么?

1 个答案:

答案 0 :(得分:1)

这是安全的,但编译器还不够智能,无法理解它。以下扰动编译得很好:

fn silliness(mut z: &mut int) {
    let tmp = z;
    z = &mut *tmp;
}

fn main() {}

playpen

这个引入临时技巧是一个有用的工具,尤其是在编写遍历数据结构的循环时,例如&mut引用。 TreeMaplet temp使用它(find_mut),它使用循环来提高效率(而不是通过递归显而易见的实现,这不需要这个技巧)。