如何进行递归可变借用?(关于IT技术)

3

这是我遇到的一些行为的最简示例:

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
我并不认为这算是“递归”——也许你可以找到更好的词? - Shepmaster
1个回答

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中有解决方法,但是快速搜索并没有立即找到。


奇怪的例子。您正在分配给 obytes,然后立即覆盖它。 - breeden

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接