我怎样才能进行递归的可变借用?

时间:2015-02-03 03:16:35

标签: rust

以下是我偶然发现的一些行为的最小示例:

pub fn main() {
    let mut ibytes = "stump".as_bytes();
    let mut obytes: &mut[u8] = &mut [0u8; 1024];

    while ibytes.len() >= 2 {
        obytes[0] = ibytes[0] >> 2;
        obytes[1] = ibytes[0] & 0x03 << 4 | ibytes[1] >> 4;

        ibytes = &ibytes[2..];
        obytes = &mut obytes[2..];
    }
}

以下代码无法编译,因为对“obytes”的切片视图操作是递归借用,而“ibytes”上的类似操作是正确的。

错误消息显示如下:

<anon>:6:9: 6:35 error: cannot assign to `obytes[..]` because it is borrowed
<anon>:6         obytes[0] = ibytes[0] >> 2;
                 ^~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:10:23: 10:29 note: borrow of `obytes[..]` occurs here
<anon>:10         obytes = &mut obytes[2..];
                                ^~~~~~
<anon>:7:9: 7:59 error: cannot assign to `obytes[..]` because it is borrowed
<anon>:7         obytes[1] = ibytes[0] & 0x03 << 4 | ibytes[1] >> 4;
                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:10:23: 10:29 note: borrow of `obytes[..]` occurs here
<anon>:10         obytes = &mut obytes[2..];
                                ^~~~~~
<anon>:10:9: 10:34 error: cannot assign to `obytes` because it is borrowed
<anon>:10         obytes = &mut obytes[2..];
                  ^~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:10:23: 10:29 note: borrow of `obytes` occurs here
<anon>:10         obytes = &mut obytes[2..];
                                ^~~~~~
<anon>:10:23: 10:29 error: cannot borrow `*obytes` as mutable more than once at a time
<anon>:10         obytes = &mut obytes[2..];
                                ^~~~~~
<anon>:10:23: 10:29 note: previous borrow of `*obytes` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*obytes` until the borrow ends
<anon>:10         obytes = &mut obytes[2..];

如何对可变“obytes”进行递归借用,就像对不可变“ibytes”所做的一样?

1 个答案:

答案 0 :(得分:2)

这是当前借阅检查员的烦恼。您可以通过使用临时中间变量明确转移可变借用来解决此问题:

pub fn main() {
    let mut ibytes = "stump".as_bytes();
    let mut obytes: &mut[u8] = &mut [0u8; 1024];

    while ibytes.len() >= 2 {
        obytes[0] = ibytes[0] >> 2;
        obytes[1] = ibytes[0] & 0x03 << 4 | ibytes[1] >> 4;

        ibytes = &ibytes[2..];
        let tmp = obytes;
        obytes = &mut tmp[2..];
    }
}

我非常确定这是一个Rust问题,但有些快速搜索并没有立即找到它。