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.
Code
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
Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does BinaryHeap Peek Mut Reprioritizes print when run?
- The script runs standalone; its 1 labeled outputs include `run`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.