Golang排序:没有实现sort.Interface(缺少Len方法)

时间:2016-09-03 18:24:03

标签: sorting go

我在Go应用程序中实现Sort接口时遇到问题。这是相关的代码:

type Group struct {
   Teams []*Team
}

type Team struct {
    Points int
 }

    type Teams []*Team

            func (slice Teams) Len() int {
                return len(slice)
            }

            func (slice Teams) Less(i, j int) bool {
                return slice[i].Points < slice[j].Points
            }

            func (slice Teams) Swap(i, j int) {
                slice[i], slice[j] = slice[j], slice[i]
            }

所以我想根据他们的观点对团队的团队进行排序。但每当我跑

sort.Sort(group.Teams)

我收到此错误:

 cannot use group.Teams (type []*Team) as type sort.Interface in argument
to sort.Sort:   []*Team does not implement sort.Interface (missing Len
method)

为什么会这样?

1 个答案:

答案 0 :(得分:6)

[]*TeamTeams不同;你需要明确地使用或转换为后者:

type Group struct {
   Teams Teams
}
sort.Sort(group.Teams)

或者:

type Group struct {
   Teams []*Team
}
sort.Sort(Teams(group.Teams))
相关问题