• Go 通过结构体指定字段进行排序


    对结构体指定字段进行排序:
      对结构体指定字段进行排序: 
    
    package main
     
    import (
        "fmt"
        "sort"
    )
     
    // 对结构体指定字段进行排序
    type User struct {
        Name string `json:"name"` // `json:"xxx"`:在结构体和json字符串字段顺序不一致的情况下:unmarshal根据tag去寻找对应字段的内容
        Age  int    `json:"age"`
    }
     
    // type Users []User
    // func SortByAge(u Users) {
    func SortByAge(u []User) {
        fmt.Printf("源数据:%+v
    ", u)
     
        sort.Slice(u, func(i, j int) bool { // desc
            return u[i].Age > u[j].Age
        })
        fmt.Printf("按Age降序:%+v
    ", u)
     
        sort.Slice(u, func(i, j int) bool { // asc
            return u[i].Age < u[j].Age
        })
        fmt.Printf("按Age升序:%+v
    ", u)
    }
     
    func main() {
        // 初始化结构体对象数组:
        // 初始化方法1:
        // users := Users{
        //     {
        //         Name: "test1",
        //         Age:  22,
        //     },
        //     {
        //         Name: "test2",
        //         Age:  19,
        //     },
        //     {
        //         Name: "test3",
        //         Age:  25,
        //     },
        // }
     
        // 初始化方法2:
        var users []User
        var u User
        u.Name = "test1"
        u.Age = 22
        users = append(users, u)
        u.Name = "test2"
        u.Age = 20
        users = append(users, u)
        u.Name = "test3"
        u.Age = 26
        users = append(users, u)
     
        SortByAge(users)
    }
     
    // 输出:
    源数据:[{Name:test1 Age:22} {Name:test2 Age:20} {Name:test3 Age:26}]
    按Age降序:[{Name:test3 Age:26} {Name:test1 Age:22} {Name:test2 Age:20}]
    按Age升序:[{Name:test2 Age:20} {Name:test1 Age:22} {Name:test3 Age:26}]
     
    此外也可使用sort.Sort()方法,不过需要自己去实现 Len()、Swap()、Less()方法,参考:golang对自定义类型排序
    
    另外,通过借助“结构体指定字段进行排序”解了一道LeetCode 347题:传送门
  • 相关阅读:
    AtCoder Grand Contest 031
    CF1010D Mars rover
    51Nod 1317 相似字符串对
    upd
    查漏补缺——字符串www.qq.com所有非空子串
    c语言查漏补缺——Win32环境下动态链接库(DLL)编程原理
    编程——二维矩阵中1所构成的块个数(孤岛问题)
    使用Windows自带远程桌面应用连接CentOS8远程桌面
    ZeroTier + NoMachine
    WinPE装入硬盘做应急系统教程
  • 原文地址:https://www.cnblogs.com/cxy2020/p/14957218.html
Copyright © 2020-2023  润新知