在Go Lang中有没有更通用的方法来实现两种堆(Max和Min)

在Go Lang中有没有更通用的方法来实现两种堆(Max和Min),go,Go,目前,Go lang doc的示例如下: 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

目前,Go lang doc的示例如下:

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
}
在ap[]int中键入
func(h IntHeap)Len()int{return Len(h)}
func(h IntHeap)Less(i,j int)bool{返回h[i]

我真的不想重复自己为最小堆创建一组方法,为最大堆创建另一组方法。有更好的方法吗?

可以使用嵌入从最小堆创建最大堆,如下所示

type MaxHeap struct {
    IntHeap
}

func (h MaxHeap) Less(i, j int) bool { return h.IntHeap[i] > h.IntHeap[j] }

请参阅一个工作示例。

你所说的“泛型讨论已死”是什么意思?@Volker的声明“泛型讨论已死”需要借助资源进行详细说明。