【问题标题】:How can I have a recursive mutable borrow? [duplicate]我怎样才能有一个递归可变借用? [复制]
【发布时间】: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


【解决方案1】:

这是当前借用检查器的烦恼。您可以通过使用临时中间变量清楚地转移可变借用来解决它:

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,然后立即覆盖它。
猜你喜欢
  • 1970-01-01
  • 2014-01-05
  • 2021-10-06
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 2014-01-07
  • 1970-01-01
相关资源
最近更新 更多