Consider the following Parent and Child structs:
type Parent struct { id string children []Child } type Child struct { id string }
Suppose we have a slice of Parent structs with predefined values:
parents := []Parent{ { "3", []Child{ {"2"}, {"3"}, {"1"}, }, }, { "1", []Child{ {"8"}, {"9"}, {"7"}, }, }, { "2", []Child{ {"5"}, {"6"}, {"4"}, }, }, }
Sorting Requirements:
Our goal is to sort the parents slice based on two criteria:
Solution:
To achieve this sorting, we utilize the sort.Slice function, which provides a flexible way to sort slices based on custom comparison functions. Here's the code:
<code class="go">// Sort parents by their ID sort.Slice(parents, func(i, j int) bool { return parents[i].id < parents[j].id }) // Iterate over each parent and sort their children by ID for _, parent := range parents { sort.Slice(parent.children, func(i, j int) bool { return parent.children[i].id < parent.children[j].id }) }</code>
This sorting algorithm efficiently handles both criteria, ensuring that the parents slice is ordered as desired.
Expected Result:
The sorted slice should resemble the following structure:
[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]
The above is the detailed content of How to Sort a Slice of Structs by Multiple Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!