Home > database >  Sorting in Go lang Interface
Sorting in Go lang Interface

Time:11-11

I am using Go. I have a dynamic data creation so I used an interface for adding my data.

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

after some operation in this interface I added some data. In this interface some of the data are dynamically adding.

In this interface I have a data like below

[
        {
             
       "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
        }
]

now I need to sort this data with each field (need to use sorting in each field)

How can I sort filed from interface

here SortBy is the field (eg 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]
                })
            }
        }

but the sorting is not working properly. What is the method for sorting interface ?

Or any alternative method exist for solving this?

CodePudding user response:

The func you need to supply to sort.Slice should return true if the value at index i is less then the value at index i. So you should replace == and != with <, or with >= for reverse sorting.

Go has no implicit type casing so in your less func you will have to check the type of each field with something like a type switch and handle the comparison based on the type you find.

For example:

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")

    }
})
  • Related