我在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)
为什么会这样?
答案 0 :(得分:6)
[]*Team
与Teams
不同;你需要明确地使用或转换为后者:
type Group struct {
Teams Teams
}
sort.Sort(group.Teams)
或者:
type Group struct {
Teams []*Team
}
sort.Sort(Teams(group.Teams))