How to Implement a Priority Queue (Heap) in Go

Implement a Go priority queue by defining a custom type that satisfies the container/heap.Interface methods.

Use the container/heap package to implement a priority queue by defining a custom type that satisfies the heap.Interface interface.

package main

import (
	"container/heap"
	"fmt"
)

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
}

func main() {
	pq := make(PriorityQueue, 0)
	heap.Init(&pq)
	heap.Push(&pq, &Item{"task1", 1, 0})
	heap.Push(&pq, &Item{"task2", 2, 1})
	fmt.Println(heap.Pop(&pq))
}