TIL about a sorting slices of composite data structures using sort.Slice
1 function. This can be done using user defined compare functions.
Let’s say we have a structure as follows:
import "sort"
// ...
type Project struct {
Cost int
Profit int
}
projects := []Project{
{
Cost: 3,
Profit: 5,
},
{
Cost: 4,
Profit: 5,
},
{
Cost: 6,
Profit: 2,
},
{
Cost: 54,
Profit: -3,
},
}
/* We can sort the above slice by profit (in ASC order) using the following implementation */
sort.Slice(projects, func(i, j int) bool {
return projects[i].Profit < projects[j].Profit
})
The projects slice after running the above function is sorted in ascendening order.
Test this example on the go playground 2
This tool could help programmers gain back a ton of time in dev-loops. Hope you found this helpful!
π βΈ» @TnvMadhav