sort.go raw

   1  package generic
   2  
   3  import (
   4  	"reflect"
   5  	"sort"
   6  )
   7  
   8  // SortSliceByField sorts given slice of struct by passing the specified field to given compare function
   9  // given slice must be a slice of Ptr
  10  func SortSliceByField(list any, field string, compare func(any, any) bool) {
  11  	listValue := reflect.ValueOf(list)
  12  	sort.SliceStable(list, func(i, j int) bool {
  13  		field1 := listValue.Index(i).Elem().FieldByName(field).Interface()
  14  		field2 := listValue.Index(j).Elem().FieldByName(field).Interface()
  15  		return compare(field1, field2)
  16  	})
  17  }
  18