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
Release: 2024-10-29 20:07:30
Original
538 people have browsed it

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

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template