dimanche 1 janvier 2023

Function to sort list (array/slice) fields an any struct variable passed as input

I want to write a function that takes any struct variable as input and sorts the list fields in it. The list fields can be of simple type (int/string) or complex (structs) in which case they must implement some comparable interface which has getValue function returning an int and defines its order to be used for sorting.

Example -

type comparable interface {
    getValue() int
}

type innerStruct struct {
    x int
    y string
}

func (s innerStruct) getValue() int {
    return s.x
}

type outerStruct struct {
    a []innerStruct
    b []int
}

func sortListFields(in interface{}) {
    // Implement this
}

func main() {
    val := outerStruct{
        a: []innerStruct{
            {1, "abc"},
            {3, "pqr"},
            {2, "xyz"},
        },
        b: []int{9, 7, 8},
    }

    fmt.Println(sortListFields(val))
    // Should print - {[{1 abc} {2 xyz} {3 pqr}] [7 8 9]}
}

I have been trying to implement it using reflection, but haven't been able to figure out how to sort the field, once I have determined its a slice/array.

func sortListFields(in interface{}) {
    v := reflect.ValueOf(in)
    for i := 0; i < v.NumField(); i++ {
        fk := v.Field(i).Type().Kind()
        if fk == reflect.Array || fk == reflect.Slice {
            fmt.Printf("%v field is a list\n", v.Type().Field(i).Name)
            // How to sort this field ???
        }
    }
}

I have following questions with respect to this.

  • Firstly (as clear from the post), how to implement sorting for the fields ?
  • Are there any other simpler (or may be not so simple) ways with/without reflection of achieving the same ?




Aucun commentaire:

Enregistrer un commentaire