How to Use container/heap in Go

Use container/heap by defining a type that implements the heap.Interface methods and calling heap.Init, Push, and Pop.

The container/heap package provides a generic heap interface for managing priority queues in Go. You must define a type that implements the heap.Interface methods (Len, Less, Swap, Push, Pop) and then use heap.Init, heap.Push, and heap.Pop to manage the data structure.

import "container/heap"

type Item struct {
    value string
    priority int
    index int
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool { return pq[i].priority < pq[j].priority }
func (pq PriorityQueue) Swap(i, j int) {
    pq[i], pq[j] = pq[j], pq[i]
    pq[i].index = i
    pq[j].index = j
}
func (pq *PriorityQueue) Push(x any) {
    item := x.(*Item)
    item.index = len(*pq)
    *pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() any {
    old := *pq
    n := len(old)
    item := old[n-1]
    old[n-1] = nil
    item.index = -1
    *pq = old[0 : n-1]
    return item
}

pq := &PriorityQueue{}
heap.Init(pq)
heap.Push(pq, &Item{"task1", 1, 0})
heap.Pop(pq)