github.com/traefik/yaegi@v0.15.1/_test/heap.go (about) 1 // This example demonstrates an integer heap built using the heap interface. 2 package main 3 4 import ( 5 "container/heap" 6 "fmt" 7 ) 8 9 // An IntHeap is a min-heap of ints. 10 type IntHeap []int 11 12 func (h IntHeap) Len() int { return len(h) } 13 func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } 14 func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 15 16 func (h *IntHeap) Push(x interface{}) { 17 // Push and Pop use pointer receivers because they modify the slice's length, 18 // not just its contents. 19 *h = append(*h, x.(int)) 20 } 21 22 func (h *IntHeap) Pop() interface{} { 23 old := *h 24 n := len(old) 25 x := old[n-1] 26 *h = old[0 : n-1] 27 return x 28 } 29 30 // This example inserts several ints into an IntHeap, checks the minimum, 31 // and removes them in order of priority. 32 func main() { 33 h := &IntHeap{2, 1, 5} 34 heap.Init(h) 35 heap.Push(h, 3) 36 fmt.Printf("minimum: %d\n", (*h)[0]) 37 fmt.Println("h:", h) 38 for h.Len() > 0 { 39 fmt.Printf("%d ", heap.Pop(h)) 40 } 41 } 42 43 // Output: 44 // minimum: 1 45 // h: &[1 2 5 3] 46 // 1 2 3 5