Manage A Priority Queue With IntHeap

Implement container/heap.Interface on an int slice, then drive Init, Push, and Pop so values always come out in priority order without sorting.

GoCli Tooling

Code

gosnippet
35 lines
package main

import (
	"container/heap"
	"fmt"
)

// IntHeap 实现 heap.Interface:最小堆,pop 顺序即优先级顺序
type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // priority queue: smaller first
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{5, 1, 3}
	heap.Init(h) // 建堆:O(n)
	heap.Push(h, 2)
	heap.Push(h, 0)

	fmt.Println("pop order:")
	for h.Len() > 0 {
		fmt.Print(heap.Pop(h), " ")
	}
	fmt.Println()
}

How the snippet works

The snippet is organized around the functions Len, Less, Swap and Push.

Repetition is confined to for h.Len() > 0 — the rest of the file is straight-line.

What to watch for

  • Runs with what the toolchain already gives you — nothing extra.

Applying it

Entry signature: func (h IntHeap) Len() int

Running the file prints labeled results such as pop order: — each operation’s effect is visible in the output.

The entry point wires Push, Len and Pop together — run it once and the whole demo flows.

Statements that carry the weight

func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // priority queue: smaller first
func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h IntHeap) Len() int           { return len(h) }

Interactive Tools for This Topic

FAQ

What does Manage A Priority Queue With IntHeap print when run?
Running the file directly is enough — expect labeled output lines such as `pop order:`.