Avatar ·

What is the simplest way to sort an array of structs by an arbitrary field in Go?

Hello everyone! I just started learning Go and ran into a sorting problem. I have an array of User structs:

\n\n
type User struct {\n    Name string\n    Age  int\n    Score float64\n}\n\nusers := []User{\n    {"Anna", 25, 88.5},\n    {"Boris", 30, 92.1},\n    {"Victor", 22, 85.0},\n}
\n\n

I need to sort this array by different fields depending on user choice: sometimes by name (alphabetically), sometimes by age, sometimes by score. I know that Go has the sort package, but for each field I have to write a separate function with Less(i, j int) bool. This is very inconvenient, especially if there are many fields.

\n\n

For example, sorting by age:

\n\n
sort.Slice(users, func(i, j int) bool {\n    return users[i].Age < u