在 Go lang 界面中排序

Sorting in Go lang Interface

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

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 是字段(例如 Career-Business Owner,Career-Entry-level,date created, hive_id,name,users)

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

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

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

如果索引 i 的值小于索引 i 的值,则您需要提供给 sort.Slicefunc 应该 return 为真。所以你应该用<替换==!=,或者用>=进行反向排序。

Go 没有隐式类型大小写,因此在您的 less 函数中,您必须使用 type switch 之类的东西检查每个字段的类型,并根据您找到的类型处理比较。

例如:

sort.Slice(hives, func(i, j int) bool {
    aInt := hives[i][gpi.SortBy]
    bInt := hives[j][gpi.SortBy]
    switch a := aInt(type) {
    case int:
        if b, ok := bInt.(int); ok {
            return a < b
        }
        panic("can't compare dissimilar types")
        
    case string:
        if b, ok := bInt.(string); ok {
            return a < b
        }
        panic("can't compare dissimilar types")

    default:
        panic("unknown type")

    }
})