Sorting a Slice of Structs with Nested Slices
In Go, you can sort slices of custom structs using the built-in sort package. Consider the following code that defines two structs, Parent and Child, representing a parent-child relationship:
<code class="go">type Parent struct { id string children []Child } type Child struct { id string }</code>
Assume you have a slice of Parent structs and want to sort them based on two criteria:
Sorting Criteria:
Solution:
The provided code snippet addresses the sorting requirement:
``
// sort each Parent in the parents slice by Id
sort.Slice(parents, func(i, j int) bool {
return parents[i].id < parents[j].id })
// for each Parent, sort each Child in the children slice by Id
for _, parent := range parents {
sort.Slice(parent.children, func(i, j int) bool { return parent.children[i].id < parent.children[j].id })
}
``
The sort.Slice function directly operates on slices, eliminating the need for intermediate containers.
The result aligns with the expected output:
[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]
The above is the detailed content of How do you sort a slice of structs with nested slices in Go based on multiple criteria?. For more information, please follow other related articles on the PHP Chinese website!