douran7929
douran7929
2016-09-03 18:24

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

已采纳

I´m having issues implementing the Sort interface in my Go app. Here´s the relevant code:

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]
            }

So I wanna sort the groups´ teams on based on their points. But whenever I run

sort.Sort(group.Teams)

I get this error:

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

Why is this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dougan7523 dougan7523 5年前

    []*Team is not the same as Teams; you need to explicitly use or cast to the latter:

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

    Or:

    type Group struct {
       Teams []*Team
    }
    sort.Sort(Teams(group.Teams))
    
    点赞 评论 复制链接分享

为你推荐