Generic Min Heap Over Container Heap

Wrap any cmp.Ordered type in a container/heap min-heap with the five heap.Interface methods, so pop always yields the smallest value.

GoData Integrity

Code

gosnippet
36 lines
package main

import (
	"cmp"
	"container/heap"
	"fmt"
)

// Heap adapts any cmp.Ordered type into a generic min-heap:
// smallest value pops first
type Heap[T cmp.Ordered] struct {
	data []T
}

func (h Heap[T]) Len() int           { return len(h.data) }
func (h Heap[T]) Less(i, j int) bool { return h.data[i] < h.data[j] }
func (h Heap[T]) Swap(i, j int)      { h.data[i], h.data[j] = h.data[j], h.data[i] }

func (h *Heap[T]) Push(v any) { h.data = append(h.data, v.(T)) }

func (h *Heap[T]) Pop() any {
	old := h.data
	n := len(old)
	v := old[n-1]
	h.data = old[:n-1]
	return v
}

func main() {
	h := &Heap[string]{data: []string{"pear", "apple", "fig"}}
	heap.Init(h)
	heap.Push(h, "date")
	for h.Len() > 0 {
		fmt.Println(heap.Pop(h))
	}
}

Reading the snippet

Generic Min Heap Over Container Heap is built around the functions Len, Less, Swap and Push.

Iteration happens inside for h.Len() > 0 — everything outside it runs once.

Points of care

  • No package manager in the path — each call lands on a built-in API.

Putting it to use

Signature: func (h Heap[T]) Len() int

main sequences Push, Len and Pop; executing the file runs that flow once.

Core lines

func (h Heap[T]) Less(i, j int) bool { return h.data[i] < h.data[j] }
func (h *Heap[T]) Push(v any) { h.data = append(h.data, v.(T)) }
func (h Heap[T]) Len() int           { return len(h.data) }

Interactive Tools for This Topic

FAQ

How do you run Generic Min Heap Over Container Heap?
Direct execution is enough; the script has no external requirements.