I've been trying to use the Heap package in Go and I am not sure on how to initialize it.
package main import "container/heap" type PriorityMessage struct { Priority int Message string } func priorityQueue() { //WOULD THIS not initialize the heap? h := heap.Init(h PriorityMessage) } I've been trying to find examples online of how other's initialized their heaps and all of them seem to create their own versions of the Go heap package everytime. Would calling the heap.Init(h Interface) function from the heap package not work?
52 Answers
There is the heap.Interface what you should implement first.
type Interface interface { sort.Interface Push(x interface{}) // add x as element Len() Pop() interface{} // remove and return element Len() - 1. } This means you should have the necessary methods for your PriorityMessage struct. After you pass the instance of the struct into the heap.Init(&pm).
You can find details in the godoc as linked in the comments.
Just to clarify the confusion. Go is a strongly typed language with lack of generics. So the heap package designed on the way that it's type independent. You can create your own implementation for all of the types what you want to implement. Any type implements the heap.Interface can be used by the heap package.
// // This example demonstrates an integer heap built using the heap interface. //package heap_test import ( "container/heap" "fmt" ) // An IntHeap is a min-heap of ints. 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 interface{}) { // Push and Pop use pointer receivers because they modify the slice's length, // not just its contents. *h = append(*h, x.(int)) } func (h *IntHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[0 : n-1] return x } // This example inserts several ints into an IntHeap, checks the minimum, // and removes them in order of priority. func Example_intHeap() { h := &IntHeap{2, 1, 5} heap.Init(h) heap.Push(h, 3) fmt.Printf("minimum: %d\n", (*h)[0]) for h.Len() > 0 { fmt.Printf("%d ", heap.Pop(h)) } // Output: // minimum: 1 // 1 2 3 5 } 2