On Sun, Apr 12, 2020 at 8:28 PM Ram Kumar <forwarding...@gmail.com> wrote:
>
> Documentation for "container/heap" says
>
> Package heap provides heap operations for any type that implements 
> heap.Interface.
>
> heap.Interface is
>
> type Interface interface {
>     sort.Interface
>     Push(x interface{}) // add x as element Len()
>     Pop() interface{}   // remove and return element Len() - 1.
> }
>
> The example program provided in the documentation has these methods
>
> // 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
> }
>
> heap.Push() and Pop() are implemented by *IntHeap and the sort.Interface is 
> implemented by IntHeap. In other words heap.Interface is not implemented by 
> one single type.
>
> Doesn't this violate the requirement "Package heap provides heap operations 
> for any type that implements heap.Interface." ? Appreciate any help to 
> understand this better.

All methods of intHeap are also methods of *intHeap (see
https://golang.org/ref/spec#Method_sets).  So the type *intHeap
implements heap.Interface.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcUyoeXmHYySK23mymbA40mYUMGYpggaY151uV2DQoXOCg%40mail.gmail.com.

Reply via email to