Home  >  Article  >  Backend Development  >  How to Sort a Slice of Structs with Nested Slice Fields in Go?

How to Sort a Slice of Structs with Nested Slice Fields in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 06:18:29433browse

How to Sort a Slice of Structs with Nested Slice Fields in Go?

Sorting by Slice Fields

In Go, you may encounter scenarios where you need to sort slices of structs that contain further nested slice fields. Consider the example below:

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

type Child struct {
    id string
}</code>

Suppose you have a slice of Parent structs with the following values:

<code class="go">parents := make([]Parent, 0)

p1 := Parent {
    "3",
    []Child {
        {"2"},
        {"3"},
        {"1"},
    },
}

p2 := Parent {
    "1",
    []Child {
        {"8"},
        {"9"},
        {"7"},
    },
}

p3 := Parent {
    "2",
    []Child {
        {"5"},
        {"6"},
        {"4"},
    },
}             

parents = append(parents, p1, p2, p3)</code>

The goal is to sort the parents slice based on two criteria:

  1. First, sort by Parent.id.
  2. Within each parent, sort the children slice by Child.id.

Solution:

To achieve the desired sorting, you can use the sort.Slice function to sort the parent slice and nested child slices. Here's the code:

<code class="go">// 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})
}</code>

This code sorts the parents slice first, ensuring that parents are arranged in ascending order based on their id field. Subsequently, for each parent, it sorts the children slice in the same manner.

Expected Result:

<code class="go">[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]</code>

The above is the detailed content of How to Sort a Slice of Structs with Nested Slice Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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