File: sort.go

package info (click to toggle)
golang-github-scaleway-scaleway-sdk-go 1.0.0~beta12-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,000 kB
  • sloc: javascript: 160; sh: 70; makefile: 3
file content (17 lines) | stat: -rw-r--r-- 551 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package generic

import (
	"reflect"
	"sort"
)

// SortSliceByField sorts given slice of struct by passing the specified field to given compare function
// given slice must be a slice of Ptr
func SortSliceByField(list interface{}, field string, compare func(interface{}, interface{}) bool) {
	listValue := reflect.ValueOf(list)
	sort.SliceStable(list, func(i, j int) bool {
		field1 := listValue.Index(i).Elem().FieldByName(field).Interface()
		field2 := listValue.Index(j).Elem().FieldByName(field).Interface()
		return compare(field1, field2)
	})
}