Go 语言界面中的排序

我正在使用围棋。我有一个动态数据创建,所以我使用一个界面来添加我的数据。


hives := make([]map[string]interface{}, lenHive)

在此界面中进行一些操作后,我添加了一些数据。在这个界面中,一些数据是动态添加的。


在这个界面中,我有如下数据


[

        {

             

       "Career-Business Owner": 0,

            "Career-Entry-level": 0,

            "Dependents-School age children (5-18)": 0,

            "date created": "2021-10-22T13:44:32.655Z",

            "date created": "2021-11-04T05:03:53.805Z",

            "hive_id": 114,

            "name": "Rule test1122-Hive 38",

            "users": 3

        },

        {

            "Career-Business Owner": 0,

            "Career-Entry-level": 0,

            "Dependents-School age children (5-18)": 0,

            "date created": "2021-10-22T13:44:32.655Z",

            "hive_id": 65,

            "name": "Rule hive44555-Hive 8",

            "users": 0

        }

]

现在我需要对每个字段的数据进行排序(需要在每个字段中使用排序)


如何从界面排序文件


这里的 SortBy 是字段(例如职业-企业主、职业-入门级、创建日期、hive_id、名称、用户)


 if SortBy != "" {

            if SortOrder == "desc" {

                sort.Slice(hives, func(i, j int) bool {

                    return hives[i][gpi.SortBy] == hives[j][gpi.SortBy]

                })

            } else {

                sort.Slice(hives, func(i, j int) bool {

                    return hives[i][gpi.SortBy] != hives[j][gpi.SortBy]

                })

            }

        }

但排序工作不正常。界面排序的方法是什么?


或者有任何替代方法可以解决这个问题?


皈依舞
浏览 120回答 1
1回答

紫衣仙女

如果索引 i 处的值小于索引 i 处的值,您需要提供的func应该返回 true。sort.Slice因此,您应该将==and!=替换为<,或 with>=进行反向排序。Go 没有隐式类型大小写,因此在您的lessfunc 中,您必须使用类型开关之类的东西检查每个字段的类型,并根据您找到的类型处理比较。例如:sort.Slice(hives, func(i, j int) bool {&nbsp; &nbsp; aInt := hives[i][gpi.SortBy]&nbsp; &nbsp; bInt := hives[j][gpi.SortBy]&nbsp; &nbsp; switch a := aInt(type) {&nbsp; &nbsp; case int:&nbsp; &nbsp; &nbsp; &nbsp; if b, ok := bInt.(int); ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return a < b&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; panic("can't compare dissimilar types")&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; case string:&nbsp; &nbsp; &nbsp; &nbsp; if b, ok := bInt.(string); ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return a < b&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; panic("can't compare dissimilar types")&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; panic("unknown type")&nbsp; &nbsp; }})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go