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:
type Parent struct {
id string
children []Child
}
type Child struct {
id string
}
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// 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}
``The sort.Slice function directly operates on slices, eliminating the need for intermediate containers.
- It sorts the parents slice based on Parent.id.
- For each parent in the sorted parents slice, it sorts the children slice based on Child.id using a nested loop.
The result aligns with the expected output:
[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3