Sorting 什么';我的golang stldib排序出了什么问题?

Sorting 什么';我的golang stldib排序出了什么问题?,sorting,go,Sorting,Go,我正在尝试按结构的一个字段对(Golang)切片进行排序 我看了很多例子,去了游乐场和文档,我觉得我明白了,但我仍然不能让我的代码正常工作 package main import ( "fmt" "sort" ) type Method struct { MethodNumber int `json:"methodNumber"` MethodRank int `json:"rank"` MethodRMSE float

我正在尝试按结构的一个字段对(Golang)切片进行排序

我看了很多例子,去了游乐场和文档,我觉得我明白了,但我仍然不能让我的代码正常工作

package main

import (
    "fmt"
    "sort"
)

type Method struct {
    MethodNumber int       `json:"methodNumber"`
    MethodRank   int       `json:"rank"`
    MethodRMSE   float64   `json:"error"`
    Forecast     []float64 `json:"forecast"`
}

// extra stuff for sorting.
type ByError []Method

func (s ByError) Len() int {
    return len(s)
}
func (s ByError) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}
func (s ByError) Less(i, j int) bool {
    return s[i].MethodRMSE < s[i].MethodRMSE
}

func main() {

    xs := make([]Method, 0)
    fmt.Println(len(xs))
    xs = append(xs, Method{MethodNumber: 1, MethodRMSE: 10})
    xs = append(xs, Method{MethodNumber: 2, MethodRMSE: 8})
    xs = append(xs, Method{MethodNumber: 3, MethodRMSE: 6})
    xs = append(xs, Method{MethodNumber: 4, MethodRMSE: 4})

    fmt.Printf("%+v \n", xs)
    sort.Sort(ByError(xs))
    fmt.Printf("%+v \n", xs)
    sort.Sort(sort.Reverse(ByError(xs)))
    fmt.Printf("%+v \n", xs)


}
主程序包
进口(
“fmt”
“排序”
)
类型方法结构{
MethodNumber int`json:“MethodNumber”`
MethodRank int`json:“rank”`
MethodRMSE float64`json:“错误”`
Forecast[]float64`json:“Forecast”`
}
//额外的分类材料。
键入ByError[]方法
func(s ByError)Len()int{
返回透镜(s)
}
func(s ByError)交换(i,j int){
s[i],s[j]=s[j],s[i]
}
func(s ByError)减去(i,j int)bool{
返回s[i].MethodRMSE
我的非工作代码:

在副本附近工作:(来自另一个SO用户)

我的应该通过RMSE进行排序,但它根本不会改变顺序。现在,我的围棋游戏的结果应该是让它按RMSE升序排序,然后反向排序

这里输入错误

func (s ByError) Less(i, j int) bool {
    return s[i].MethodRMSE < s[i].MethodRMSE
}
func(s ByError)减去(i,j int)bool{
返回s[i].MethodRMSE
应该是

func (s ByError) Less(i, j int) bool {
    return s[i].MethodRMSE < s[j].MethodRMSE
}
func(s ByError)减去(i,j int)bool{
返回s[i].MethodRMSE
因为有点难看,第一个(错误的)版本将该项与自身进行比较(两个索引都是
i
)。第二个在这里正确地使用了
i
j

打字

func (s ByError) Less(i, j int) bool {
    return s[i].MethodRMSE < s[i].MethodRMSE
}
func(s ByError)减去(i,j int)bool{
返回s[i].MethodRMSE
应该是

func (s ByError) Less(i, j int) bool {
    return s[i].MethodRMSE < s[j].MethodRMSE
}
func(s ByError)减去(i,j int)bool{
返回s[i].MethodRMSE

因为有点难看,第一个(错误的)版本将该项与自身进行比较(两个索引都是
i
)。第二个函数正确地使用
i
j

Less
函数中,您在比较的两侧使用元素
i
。在
Less
函数中,您在比较的两侧使用元素
i