gpt4 book ai didi

sorting - Golang Sort :does not implement sort. 接口(interface)(缺少 Len 方法)

转载 作者:IT王子 更新时间:2023-10-29 01:24:02 26 4
gpt4 key购买 nike

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

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)

这是为什么?

最佳答案

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

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

或者:

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

关于sorting - Golang Sort :does not implement sort. 接口(interface)(缺少 Len 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39310088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com