A motivating example:
Implementing various scheduling "strategies", which sort a list of Jobs.
type Job struct {
weight int
length int
}
// Given a slice of Jobs, re-order them.
type Strategy func([]Job) []Job
func Schedule(jobs []Job, strat Strategy) []Job {
return strat(jobs)
}
One very simple strategy is to execute the shortest jobs first (disregarding their weight/priority).
func MinCompletionTimes(job []Job) []Job {
// Hmm...
}
Well, this strategy is nothing more than a sort on job.length, so let's use the sort package. Define a custom type, and implement sort.Interface...
type JobSlice []Job // Should probably be called MinCompletionTimesJobSlice
func (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]
}
Hooray, now to back to our simple strategy...
func MinCompletionTimes(jobs []Job) []Job {
sort.Sort([]JobSlice(jobs)) // cannot convert jobs (type []Job) to type []JobSlice
return jobs
}
Er...