Sorting user defined collection in multiple ways

94 views
Skip to first unread message

srinik....@gmail.com

unread,
Jul 21, 2017, 9:17:29 AM7/21/17
to golang-nuts
Hi,
I have below requirement, could any one suggest on how i can achieve in go lang using https://golang.org/pkg/sort/.
- I have user defined data structure called Employee with attributes "age", name and sal.  I want to write three different go functions that sorts based on age, name and sal.
example:-
  sortEmployeeByAge(employeelist)
  sortEmployeeByName(employeelist)
  sortEmployeeBySal(employeelist)

Thanks,
Srinivas K

Jan Mercl

unread,
Jul 21, 2017, 9:26:56 AM7/21/17
to srinik....@gmail.com, golang-nuts
On Fri, Jul 21, 2017 at 3:17 PM <srinik....@gmail.com> wrote:

> - I have user defined data structure called Employee with attributes "age", name and sal. I want to write three different go functions that sorts based on age, name and sal.

Are you sorting a slice? https://golang.org/pkg/sort/#Slice

--

-j

Val

unread,
Jul 21, 2017, 10:17:13 AM7/21/17
to golang-nuts
Hello Srinivas

The traditional way to achieve this in go (as showcased here and here) is, to :
- declare a named type of slice
- implement 3 methods Len, Less, Swap
- call sort.Sort

(each attribute age, name, sal, needs its own type declaration and 3 method implementations).

Since Go 1.8, we can achieve basically the same with much less boilerplate code (as showcased here and here) :
- implement 1 func "less" having type  func(i, j int) bool
- call sort.Slice

(each attribute age, name, sal, needs its own "less" func).

I suggest the latter.
HTH
Valentin

Srinivas Kandula

unread,
Jul 26, 2017, 1:52:16 AM7/26/17
to golang-nuts
Thank you very much Valentin !!, This is exactly what i am looking for.

Thanks,
Srinivas K
Reply all
Reply to author
Forward
0 new messages