BinaryHeap Peek Mut Reprioritizes

Demote the failing top job in place with peek_mut: mutating through the guard and dropping it sifts the heap back into a valid max-heap.

RustResilience

Code

rustsnippet
23 lines
use std::collections::BinaryHeap;

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Job {
    priority: u8,
    id: &'static str,
}

fn main() {
    let mut queue = BinaryHeap::new();
    queue.push(Job { priority: 9, id: "render" });
    queue.push(Job { priority: 5, id: "export" });
    queue.push(Job { priority: 3, id: "cleanup" });

    // 顶部任务失败:peek_mut 借出堆顶守卫,就地降级 reprioritize
    if let Some(mut top) = queue.peek_mut() {
        top.priority = 4;
    } // 守卫析构时自动恢复堆序:降级后的任务下沉

    while let Some(job) = queue.pop() {
        println!("run {} (p{})", job.id, job.priority);
    }
}

How the code works

Everything happens inside the function main.

Iteration happens inside while let Some(job) = queue.pop() — everything outside it runs once.

Caveats

  • The whole dependency story is the language version itself.

Putting it to use

The primary signature reads fn main()

Output lines are prefixed (run), which keeps each step’s effect visible.

Core lines

while let Some(job) = queue.pop() {
    println!("run {} (p{})", job.id, job.priority);
}
if let Some(mut top) = queue.peek_mut() {
    top.priority = 4;
} // 守卫析构时自动恢复堆序:降级后的任务下沉

Interactive Tools for This Topic

FAQ

What does BinaryHeap Peek Mut Reprioritizes print when run?
The script runs standalone; its 1 labeled outputs include `run`.