How to use BinaryHeap

Use BinaryHeap to create a priority queue that automatically sorts items by importance, allowing you to push tasks and pop the highest priority one instantly.

Use std::collections::BinaryHeap to manage a priority queue where the largest element is always at the top. Implement Ord and PartialOrd for your custom types to define priority, then use push to add items and pop to retrieve the highest priority item.

use std::collections::BinaryHeap;

#[derive(Debug, PartialEq, Eq)]
struct Task {
    priority: i32,
    name: String,
}

impl Ord for Task {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.priority.cmp(&other.priority)
    }
}

impl PartialOrd for Task {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

fn main() {
    let mut heap = BinaryHeap::new();
    heap.push(Task { priority: 1, name: "Low".to_string() });
    heap.push(Task { priority: 5, name: "High".to_string() });

    if let Some(task) = heap.pop() {
        println!("Processing: {} (Priority: {})", task.name, task.priority);
    }
}