Home > Backend Development > Golang > How to sort slices using sort.Slice function in golang

How to sort slices using sort.Slice function in golang

王林
Release: 2023-11-18 09:10:56
Original
2278 people have browsed it

How to sort slices using sort.Slice function in golang

Sorting slices is a commonly used function in Golang and can be quickly implemented using the sort.Slice function. This function allows sorting slices by passing in a custom comparison function.

The sort.Slice function is defined as follows:

func Slice(slice interface{}, less func(i, j int) bool)
Copy after login

Among them, the slice parameter specifies the slice to be sorted, and the less parameter is a comparison function used to define the comparison rules of slice elements.

The following is a sample code that demonstrates how to use the sort.Slice function to sort slices:

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name string
    Age  int
}

type Persons []Person

func (p Persons) Len() int {
    return len(p)
}

func (p Persons) Less(i, j int) bool {
    return p[i].Age < p[j].Age
}

func (p Persons) Swap(i, j int) {
    p[i], p[j] = p[j], p[i]
}

func main() {
    persons := Persons{
        {"Alice", 25},
        {"Bob", 30},
        {"Charlie", 20},
        {"David", 35},
    }

    fmt.Println("Before sort:", persons)

    sort.Slice(persons, func(i, j int) bool {
        return persons[i].Age < persons[j].Age
    })

    fmt.Println("After sort:", persons)
}
Copy after login

In the above code, we define a Person structure and a Persons slice type. The Persons type implements three interfaces in the sort package: Len, Less, and Swap, thus indicating that Persons can be sorted.

In the main function, we define a persons slice instance and use the sort.Slice function to sort the slice in the following code. In this case, we define a way to sort in ascending order by the Person.Age field by passing an anonymous function as the less parameter.

Finally, we output the sorted results and you can see that the sorting has been completed.

Summary:

The sort.Slice function is a shortcut for slice sorting in Golang. We can define different collations by passing different comparison functions. When passing the comparison function in sort.Slice, we can use an anonymous function or a structure that implements the sort interface.

The above is the detailed content of How to sort slices using sort.Slice function in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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