dongmaijie5200 2015-03-22 15:41
浏览 82
已采纳

如何将排序接口实现类型作为函数参数传递?

I am writing different scheduling algorithm and would like to compare various ways of ordering jobs. I have a function on a struct that I would like to pass the type of a sort interface type to be used by the sort within the function.

type Schedule struct {
    Jobs []Job
}

type ByDifference []Job
// ByDifference implements sort.Interface

type ByRatio []Job
// ByRatio implements sort.Interface

func (s *Schedule) Schedule(OrderBy sort.Interface) {
    // Summation variables omitted

    // This fails as there is no function OrderBy()
    sort.(OrderBy(q.Jobs))

    for _, v := range q.Jobs {
        // Compute weighted sum omitted
    }

    // Output code omitted

}

Naturally, I would like to to call the Schedule function and pass some representation of ByDifference or ByRatio and have the sort use that type. My initial reading seems to lead to type reflection. Is it possible to use this design to pass a type that implements an interface to be used by sort within a function?

  • 写回答

1条回答 默认 最新

  • dougaoxian8922 2015-03-22 20:43
    关注

    Maybe this way

    type Schedule struct {
        Jobs []Job
    }
    const(
    Difference=iota
    Ratio=iota
    )
    type ByDifference Schedule
    // ByDifference implements sort.Interface
    
    type ByRatio Schedule
    // ByRatio implements sort.Interface
    
    func (s *Schedule) Schedule(order int) { // s.Schedule(Difference) for example
        // Summation variables omitted
        switch order{
            case Difference: ss:= ByDifference(*s);  sort(ss); s=&Schedule(ss)
            case Ratio: ss:= ByRatio(*s);  sort(ss); s=&Schedule(ss)
        }
    
        for _, v := range s.Jobs {
            // Compute weighted sum omitted
        }
    
        // Output code omitted
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配