您好,欢迎来到爱go旅游网。
搜索
您的当前位置:首页Go通过结构体指定字段进行排序

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

来源:爱go旅游网
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\\n\", u)

sort.Slice(u, func(i, j int) bool { // desc return u[i].Age > u[j].Age })

fmt.Printf(\"按Age降序:%+v\\n\", u)

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

fmt.Printf(\"按Age升序:%+v\\n\", 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题:传送门

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- igat.cn 版权所有 赣ICP备2024042791号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务