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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.