Home > Backend Development > Golang > How to Sort Go Structs by Custom Fields Using `sort.Slice`?

How to Sort Go Structs by Custom Fields Using `sort.Slice`?

DDD
Release: 2024-12-19 06:25:10
Original
459 people have browsed it

How to Sort Go Structs by Custom Fields Using `sort.Slice`?

Sorting Arrays of Structs by Custom Field Names in Go

In Go, sorting an array of structs by a specific field can be a complex task, especially if you require a custom key. However, with the introduction of sort.Slice in Go 1.8, this process has become significantly easier.

Consider an array of Planet structs, each containing properties such as name, aphelion, perihelion, axis, and radius. To sort these planets by their axis values, you can utilize the sort.Slice function:

package main

import (
    "log"
    "sort"
)

type Planet struct {
    Name       string
    Aphelion   float64
    Perihelion float64
    Axis       int64
    Radius     float64
}

func main() {
    mars := &Planet{
        Name:       "Mars",
        Aphelion:   249.2,
        Perihelion: 206.7,
        Axis:       227939100,
        Radius:     3389.5,
    }

    earth := &Planet{
        Name:       "Earth",
        Aphelion:   151.930,
        Perihelion: 147.095,
        Axis:       149598261,
        Radius:     6371.0,
    }

    venus := &Planet{
        Name:       "Venus",
        Aphelion:   108.939,
        Perihelion: 107.477,
        Axis:       108208000,
        Radius:     6051.8,
    }

    planets := [...]Planet{*mars, *venus, *earth}

    log.Println("Original order:", planets)

    sort.Slice(planets[:], func(i, j int) bool {
        return planets[i].Axis < planets[j].Axis
    })

    log.Println("Order after sorting by axis:", planets)
}
Copy after login

In this example, the sort.Slice function takes a slice of the planets array and a comparison function as its arguments. The comparison function determines the sorting order. In this case, the comparison function checks if the axis value of the i-th element is smaller than that of the j-th element.

The sorting operation modifies the planets array in place, so there is no need to assign the sorted result to a new variable.

It's important to note that sort.Slice modifies the original array. If you require a new sorted slice, you can explicitly create a copy of the original slice before sorting.

The above is the detailed content of How to Sort Go Structs by Custom Fields Using `sort.Slice`?. 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