"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do you sort a slice of structs with nested slices in Go based on multiple criteria?

How do you sort a slice of structs with nested slices in Go based on multiple criteria?

Published on 2024-11-08
Browse:977

How do you sort a slice of structs with nested slices in Go based on multiple criteria?

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:

  1. Sort the Parent slice by Parent.id in ascending order.
  2. For each Parent, sort the children slice by Child.id in ascending order within the parent.

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.

  1. It sorts the parents slice based on Parent.id.
  2. 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}]}]
Latest tutorial More>

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