Home >Backend Development >Golang >How to Sort a Slice of Structs by Multiple Fields in Go?

How to Sort a Slice of Structs by Multiple Fields in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 20:07:30541browse

How to Sort a Slice of Structs by Multiple Fields in Go?

Sorting Slice Objects by Multiple Fields

Sorting by Multiple Criteria

Consider the following Parent and Child structs:

type Parent struct {
    id       string
    children []Child
}

type Child struct {
    id string
}

Suppose we have a slice of Parent structs with predefined values:

parents := []Parent{
    {
        "3",
        []Child{
            {"2"},
            {"3"},
            {"1"},
        },
    },
    {
        "1",
        []Child{
            {"8"},
            {"9"},
            {"7"},
        },
    },
    {
        "2",
        []Child{
            {"5"},
            {"6"},
            {"4"},
        },
    },
}

Sorting Requirements:

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

  1. Sort Parent structs in ascending order of their id field.
  2. Within each Parent struct, sort the children slice in ascending order of the id field.

Solution:

To achieve this sorting, we utilize the sort.Slice function, which provides a flexible way to sort slices based on custom comparison functions. Here's the code:

<code class="go">// Sort parents by their ID
sort.Slice(parents, func(i, j int) bool { return parents[i].id < parents[j].id })

// Iterate over each parent and sort their children 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 sorting algorithm efficiently handles both criteria, ensuring that the parents slice is ordered as desired.

Expected Result:

The sorted slice should resemble the following structure:

[{1 [{7} {8} {9}]} {2 [{4} {5} {6}]} {3 [{1} {2} {3}]}]

The above is the detailed content of How to Sort a Slice of Structs by Multiple 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