container/heap
container/heap is a standard-library package that maintains a slice as a binary heap. You implement heap.Interface (Len, Less, Swap, Push, Pop) and call heap.Init, heap.Push, and heap.Pop.
Detailed Explanation
A heap is a binary tree in an array where each parent is less than (or greater than) its children. The smallest (or largest) element is at index 0. You want it when you always need the next-best item: Dijkstra, a priority queue of jobs, "top K" streaming.
The package does not include an element type. You bring a slice type:
type intHeap []int
and methods so Less(i, j) defines min-heap or max-heap. Push and Pop append and truncate the slice; they must be pointer receivers because they change len. heap.Push and heap.Pop then restore the heap property. Calling append yourself bypasses that property.
Init is optional if you push from empty. If you already have a slice of items, heap.Init heapifies in linear time. Pushing n items from scratch is n log n.
Index 0 is the next pop, not a sorted array. The rest of the slice is not sorted. Do not range the heap and expect order. Pop until empty if you need sorted output (heapsort). The sort package is simpler if you have all items up front and only need to sort once.
Fix and Remove. When an element's priority changes, heap.Fix(h, i) restores the property at that index. heap.Remove(h, i) deletes an arbitrary index. You need to know i, so items often store their own index if you will update them.
What it costs. Each push and pop is O(log n) comparisons and swaps. The slice is one allocation that grows like any other. For integer priorities, a hand-rolled slice plus sort.Ints on a small n can be clearer. Use container/heap when n is large or the queue is long-lived.
Code Examples
package main
import (
"container/heap"
"fmt"
)
type intHeap []int
func (h intHeap) Len() int { return len(h) }
func (h intHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h intHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *intHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *intHeap) Pop() any {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}
func main() {
h := &intHeap{3, 1, 2}
heap.Init(h)
heap.Push(h, 0)
fmt.Println(heap.Pop(h)) // 0
}Common Gotchas
`Push` and `Pop` must use pointer receivers
a value receiver cannot persist the new length.
Do not `append` to the slice except inside `Push`
you will break the heap property.
`Pop` returns `any`
a wrong type assertion panics. Keep one heap type per element type, or use a generic wrapper in your own package.
The first element is the next pop
the slice is not fully sorted.