Hi đź‘‹
In this article I want to highlight a simple pattern for sorting a slice in Go on multiple keys.
Given the following structure, let’s say we want to sort it in ascending order after Version, Generation and Time.
|
|
The way we sort slices in Go is by using the sort interface or one of the sort.Slice functions. To sort the slice after the above criteria we’ll call slice.Sort with the following function.
|
|
The slice will be sorted after the following fields: Version, Generation and Time. The trick is the switch statement and the case expression case iv.Version != jv.Version followed by the statement return iv.Version < jv.Version.
You can use this pattern whenever you want to sort slices over multiple fields in Go.
Thanks for reading! 🍻
Source Code
|
|
Output
|
|
Also, special thanks to RP.đź’–