BinaryHeap Ranks Tasks With Derived Ord

Derive Ord on a job struct field-by-field and push it into a BinaryHeap: pops come back highest priority first, and Reverse flips to a min-heap.

RustResilience

Code

rustsnippet
28 lines
use std::cmp::Reverse;
use std::collections::BinaryHeap;

// Ord 按字段声明顺序比较:先比 priority,再比 submitted_at
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Job {
    priority: u8,
    submitted_at: u32,
    name: String,
}

fn main() {
    let mut queue = BinaryHeap::new();
    queue.push(Job { priority: 1, submitted_at: 10, name: "warmup".into() });
    queue.push(Job { priority: 3, submitted_at: 20, name: "export".into() });
    queue.push(Job { priority: 3, submitted_at: 15, name: "render".into() });

    // 最大堆:priority 高的先出;同优先级里 submitted_at 大的先出
    while let Some(job) = queue.pop() {
        println!("run: {} (p{}, t{})", job.name, job.priority, job.submitted_at);
    }

    // 最小堆:把值包进 Reverse 再入堆
    let mut small = BinaryHeap::new();
    small.push(Reverse(7));
    small.push(Reverse(2));
    println!("min first: {}", small.pop().unwrap().0);
}

Walking through the code

The logic is concentrated in the function main.

One loop does the cycling here: while let Some(job) = queue.pop().

Watch out for

  • Ready as-is on a bare install of the language.

Using it

The signature for main reads: fn main()

Tags in the output mark each step: run:, min first:.

Key statements

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

Interactive Tools for This Topic

FAQ

What does BinaryHeap Ranks Tasks With Derived Ord print when run?
Execute the whole file; each printed line is prefixed with a label like `run:`, `min first:`.