In the default container/heap
package in go, there's an example for implementing a priority queue.
While looking at the sample code, it uses a slice []*Item
, and implements the heap.Interface
.
My trouble is with the following bit. Why are some functions declared with the priority queue as a slice and sometimes as a pointer to slice ?:
func (pq PriorityQueue) Swap(i, j int) {...}
// vs
func (pq *PriorityQueue) Push(x interface{}) {...}
Why isn't it always (pq PriorityQueue)
? On this other StackOverflow thread about pointer to slices, the docs say that slices are refence types, so why use pointers on them ? I'm having trouble with the fact that the official doc says something then mixes both without explaining the point of adding a pointer.
Thanks for your insights !
EDIT: Here's an example:
// original sample code from the docs:
func (pq *PriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*Item)
item.index = n
*pq = append(*pq, item)
}
// is this the same (removed pointers to slice) ?
func (pq PriorityQueue) Push(x interface{}) {
n := len(pq)
item := x.(*Item)
item.index = n
pq = append(pq, item)
}
If both functions are the same, why use a pointer now ?