【发布时间】:2015-02-03 03:16:35
【问题描述】:
这是我偶然发现的一些行为的一个最小示例:
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”所做的那样?
【问题讨论】:
-
我真的不认为这符合“递归”的条件——也许你能找到更好的词?
标签: rust