Rust 当有条件地从二进制堆弹出元素时,借用检查器不满意

Rust 当有条件地从二进制堆弹出元素时,借用检查器不满意,rust,Rust,我正在尝试编写一个简单的函数,它将从满足特定条件的二进制堆中弹出元素。函数如下所示: fn check_the_queue(mut queue: BinaryHeap<i32>) { while !queue.is_empty() { let entry = queue.peek().unwrap(); if *entry <= 0 { queue.pop(); } } 如何绕过此问题并使借阅检查器满意?错误消息非常具有描述性: &l

我正在尝试编写一个简单的函数,它将从满足特定条件的二进制堆中弹出元素。函数如下所示:

fn check_the_queue(mut queue: BinaryHeap<i32>) {
while !queue.is_empty() {
    let entry = queue.peek().unwrap();
    if *entry <= 0 {
        queue.pop();
    } 
}

如何绕过此问题并使借阅检查器满意?

错误消息非常具有描述性:

<anon>:8:13: 8:18 error: cannot borrow `queue` as mutable because it is also borrowed as immutable
<anon>:8             queue.pop();
                     ^~~~~
<anon>:5:21: 5:26 note: previous borrow of `queue` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `queue` until the borrow ends
<anon>:5         let entry = queue.peek().unwrap();
                             ^~~~~
<anon>:10:6: 10:6 note: previous borrow ends here
<anon>:4     while !queue.is_empty() {
...
<anon>:10     }
              ^
peek()
返回一个
选项
,即引用类型为
T
的值的选项。只要
条目
处于活动状态,借用就有效,直到函数结束。它指向存储在堆中的某些内容,因此它不可变地借用堆。换句话说,只要
entry
处于活动状态(直到函数结束),堆就会被永久借用

queue.pop()
以可变方式借用堆,因此,当您到达该位置时,堆是不可变地借用的,您同时尝试以可变方式借用它

借用检查器规则规定,您不能同时可变和不变地借用某些内容,因此您有一个问题

要解决这个问题,要想办法避免同时借款两次。例如,您可以这样做:

fn check_the_queue(mut queue: BinaryHeap<i32>) {
    while !queue.is_empty() {
        if *queue.peek().unwrap() <= 0 {
            queue.pop();
        } 
    }
}
fn检查队列(mut队列:二进制堆){
while!queue.is_为空(){
如果*queue.peek().unwrap())
let entry = queue.peek().unwrap();
fn check_the_queue(mut queue: BinaryHeap<i32>) {
    while !queue.is_empty() {
        if *queue.peek().unwrap() <= 0 {
            queue.pop();
        } 
    }
}