dounao1875 2012-12-06 21:21
浏览 38
已采纳

一种将一种类型的切片转换为等效类型的切片的优雅方法?

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

  • 写回答

1条回答 默认 最新

  • duanbai1974 2012-12-06 21:48
    关注

    First of all, I don't see Jobs defined anywhere even though you use it like jobs []Jobs.

    I think you mean Job since the error states cannot convert jobs (type []Job), so I'll assume that when you're doing []Jobs, you really mean []Job.


    If so, then with this, y You're trying to convert a slice of Job to a slice of JobSlice, the which has an underlying type of []Job.

    []JobSlice(jobs) // converting a slice of Job to a slice of slices of Job?
    

    In other words, you're trying to convert []Job to effectively [][]Job. Instead I think you just wanted to convert your []Job to JobSlice

    JobSlice(jobs)
    

    So taking out a bunch of the code, you can see that this conversion will work.

    type Job struct {
        weight int
        length int
    }
    
    type JobSlice []Job
    
    func main() {
        x := []Job{{},{}}
    
        y := JobSlice(x)
        z := []Job(y)
    
        fmt.Println(x, y, z)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等