我想做一个最小和最大的整数堆:
package main
import (
"container/heap"
"fmt"
)
func main() {
hi := make(IntHeap, 0)
for number := 10; number >= 0; number-- {
hi = append(hi, number)
}
heap.Init(&hi)
fmt.Println(heap.Pop(&hi))
fmt.Println(heap.Pop(&hi))
fmt.Println(heap.Pop(&hi))
}
// 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{}) {
*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
}
type IntMaxHeap IntHeap
func (h IntMaxHeap) Less(i, j int) bool { return h[i] > h[j] }
如果我想改用 IntMaxHeap
,我会得到:
./median_stream.go:14: cannot use &hi (type *IntMaxHeap) as type heap.Interface in function argument:
*IntMaxHeap does not implement heap.Interface (missing Len method)
./median_stream.go:15: cannot use &hi (type *IntMaxHeap) as type heap.Interface in function argument:
*IntMaxHeap does not implement heap.Interface (missing Len method)
./median_stream.go:16: cannot use &hi (type *IntMaxHeap) as type heap.Interface in function argument:
*IntMaxHeap does not implement heap.Interface (missing Len method)
./median_stream.go:17: cannot use &hi (type *IntMaxHeap) as type heap.Interface in function argument:
*IntMaxHeap does not implement heap.Interface (missing Len method)
我怎样才能制作两个结构(“类”),而它们只有一个方法实现不同?工作版本应该从堆中打印 3 个最大的数字。
最佳答案
当您在 Go 中声明一个新类型时,它不会继承底层类型的方法。如果您确实想继承方法,请考虑使用组合:
type IntMaxHeap struct {
IntHeap
}
func (h IntMaxHeap) Less(i, j int) bool { return h.IntHeap[i] > h.IntHeap[j] }
如果您有一个准备好的 IntHeap
(或任何 []int
slice ,就此而言),您可以使用 IntMaxHeap{slice} 构造此类型
无需重新实现其他方法。
此模式对于声明用于 sort
包的多个排序非常有用,而无需重复方法。
关于go - 制作两个结构,它们与一种方法实现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24321836/