Home > Backend Development > Golang > 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?

DDD
Release: 2024-10-28 21:10:03
Original
1075 people have browsed it

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:

<code class="go">type Parent struct {
    id       string
    children []Child
}

type Child struct {
    id string
}</code>
Copy after login

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 < parents[j].id })
Copy after login

// 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 })
Copy after login

}
``

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}]}]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template