一个激励人心的例子:实施各种调度“策略”,对“作业”列表进行排序。type Job struct { weight int length int}// Given a slice of Jobs, re-order them.type Strategy func([]Job) []Jobfunc Schedule(jobs []Job, strat Strategy) []Job { return strat(jobs)}一种非常简单的策略是首先执行最短的作业(不考虑其权重/优先级)。func MinCompletionTimes(job []Job) []Job { // Hmm... }嗯,这种策略只不过是对job.length进行排序,因此让我们使用sort包。定义一个自定义类型,并实现sort.Interface ...type JobSlice []Job // Should probably be called MinCompletionTimesJobSlicefunc (js JobSlice) Len() { return len(js)}func (js JobSlice) Less(i, j int) bool { return js[i].length < js[j].length}func (js JobSlice) Swap(i, j int) { js[i], js[j] = js[j], js[i]}好了,现在回到我们的简单策略...func MinCompletionTimes(jobs []Job) []Job { sort.Sort([]JobSlice(jobs)) // cannot convert jobs (type []Job) to type []JobSlice return jobs}
1 回答
- 1 回答
- 0 关注
- 144 浏览
添加回答
举报
0/150
提交
取消