dongya4335 2014-06-20 07:13
浏览 3
已采纳

使两种结构与一种方法的实现不同

I want to make a min and max heap of integers:

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] }

If I want to use IntMaxHeap instead, I am getting:

./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)

How can I make two structs ("classes") which differ with just one method implementation? The working version should print 3 biggest numbers from the heap.

  • 写回答

2条回答 默认 最新

  • dqnz43863 2014-06-20 08:31
    关注

    When you declare a new type in Go, it doesn't inherit the methods of the underlying type. If you do want to inherit methods, consider using composition:

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

    If you have a primed IntHeap (or any []int slice, for that matter), you can construct this type with IntMaxHeap{slice} without needing to reimplement the other methods.

    This pattern can be quite useful to declare multiple orderings for use with the sort package, without duplicating methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM