package main

import (
    "fmt"
    "sort"
)

func main() {
    TestSortAsc()
    TestReverse()
}

func TestSortAsc() {
    data := []string{"4", "1", "5"}
    sort.Strings(data)
    //升序
    fmt.Println("data:", data)
}

func TestSortAscInts() {
     // Create s slice of int
    data := []int {9,3,5,1,2}
    sort.Ints(data)
    //升序
    fmt.Println("data:", data)
}

func TestReverse() {
    data := []string{"4", "1", "5"}
    sort.Sort(sort.Reverse(sort.StringSlice(data))) //降序
    //降序
    fmt.Println("data:", data)
}

第三方包

github.com/duke-git/lancet/v2/slice

import (
    "fmt"
    "github.com/duke-git/lancet/v2/slice"
)

func main() {
    type User struct {
        Name string
        Age  uint
    }

    users := []User{
        {Name: "a", Age: 21},
        {Name: "b", Age: 15},
        {Name: "c", Age: 100}}

    err := slice.SortByField(users, "Age", "desc")
    if err != nil {
        return
    }

    fmt.Println(users)

    // Output:
    // [{c 100} {a 21} {b 15}]
}