Sorting Array of Struct Using Inbuilt Sort Package in Golang

sorting array of struct using inbuilt sort package#

go have sort package which have many inbuilt functions available for sorting integers, string, and even for complex structure like structs and maps

in this post we will sort array of struct. suppose we have created a below array of employee which have name and age fields.


type Employee struct {
    Name string
    Age int
}

employees := []Employee{
        Employee{Name: "John", Age: 32},
        Employee{Name: "Denver", Age:40},
        Employee{Name: "Albert", Age:25},
}

for sorting above data we have satisfy the Interface interface which is used inside the Sort() function that interface have three methods which we have to implement

  • Len() int
  • Less(i, j int) bool
  • Swap(i, j int)

as we can see our employees variable have array type so for attaching method to that we have to create on more type on top of that array type like below.

``


type SortEmployee []Employee

func (s SortEmployee) Len() int {
	return len(s)
}
func (s SortEmployee) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s SortEmployee) Less(i, j int) bool {
	return s[i].Age > s[j].Age
}

Len() will calculate the length of array

Swap will swap the values if it is less than in condition like we do in bubble sort algorithm.

Less() will simply compare and return lesser value. if we change the logic in Less function we can achieve ascending an descending order.

Now look at the below completed code for sorting you will get the idea how it works.



package main

import (
	// "encoding/json"
	"fmt"
	"sort"
)

type Employee struct {
	Name string
	Age  int
}

type SortEmployee []Employee

func (s SortEmployee) Len() int {
	return len(s)
}
func (s SortEmployee) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s SortEmployee) Less(i, j int) bool {
	return s[i].Age > s[j].Age
}


func main() {
	employees := []Employee{
        Employee{Name: "John", Age: 32},
        Employee{Name: "Denver", Age:40},
        Employee{Name: "Albert", Age:25},
    }

	sort.Sort(SortEmployee(employees))

	fmt.Println(e)

}

Output will be look like below one#

[{Denver 40} {John 32} {Albert 25}]

comments powered by Disqus