go - 制作两个结构,它们与一种方法实现不同

标签 go

我想做一个最小和最大的整数堆:

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/

相关文章:

go - 如何向 Go/LiteIDE 添加 include 目录?

go - 无法加载包 : github. com/dmgk/faker 期望导入 "syreclabs.com/go/faker"

golang 自定义结构未定义,无法正确导入

go - 检查 golang 中的二进制完整性

go - 如何将子目录/子域放在另一台服务器(或共享主机)中

encoding - 我如何在 Golang 中将一个 16 位整数写入多个字节?

go - 如何自定义 go-present 模板?

json - 如何将具有动态字段的 JSON 对象映射到 Go 结构

http - 如何查看 HTTP/HTTPS 与 HTTP 客户端的交互

Linux 用户命名空间