Golang对结构体进行排序

xiaohai 2019-12-23 10:28:00 6058人围观 标签: Go  排序 
简介在PHP中,对二维数组排序还是非常简单的,但是在Golang中对二位数据排序显的就稍显麻烦,但是我们还是可以通过结构体来进行排序,本文主要记录Golang如何通过结构体的多个字段来进行排序。
1、方法一,通过实现sort.Interface接口来进行排序

这里直接上代码:

package main import ( "fmt" "sort" ) type Student struct { Name string //名称 IsOnline int64 //是否在线 Integral int64 //积分 Gold float64 //金币 } type Students []*Student // 实现sort.Interface接口取元素数量方法 func (c Students) Len() int { return len(c) } // 实现sort.Interface接口比较元素方法 func (c Students) Less(i, j int) bool { //先是否根据是否在线进行排序 if c[i].IsOnline != c[j].IsOnline { return c[i].IsOnline > c[j].IsOnline } //在通过积分进行排序 if c[i].Integral != c[j].Integral { return c[i].Integral > c[j].Integral } //最后通过金币排序 return c[i].Gold > c[j].Gold } // 实现sort.Interface接口交换元素方法 func (c Students) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func main() { // 准备英雄列表 students := Students{ &Student{"吕布", 1, 12, 11.0}, &Student{"张飞", 0, 3, 12.1}, &Student{"关羽", 0, 6, 9.9}, &Student{"刘备", 1, 12, 0}, &Student{"诸葛亮", 1, 0, 1}, &Student{"曹操", 0, 1, 1000}, } // 使用sort包进行排序 sort.Sort(students) // 遍历英雄列表打印排序结果 for _, v := range students { fmt.Printf("%+v\n", v) } }

结果:

>go run test.go &{Name:吕布 IsOnline:1 Integral:12 Gold:11} &{Name:刘备 IsOnline:1 Integral:12 Gold:0} &{Name:诸葛亮 IsOnline:1 Integral:0 Gold:1} &{Name:关羽 IsOnline:0 Integral:6 Gold:9.9} &{Name:张飞 IsOnline:0 Integral:3 Gold:12.1} &{Name:曹操 IsOnline:0 Integral:1 Gold:1000}
1、方法二,使用sort.Slice进行切片元素排序
package main import ( "fmt" "sort" ) type Student struct { Name string //名称 IsOnline int64 //是否在线 Integral int64 //积分 Gold float64 //金币 } type Students []*Student func main() { // 准备英雄列表 students := Students{ &Student{"吕布", 1, 12, 11.0}, &Student{"张飞", 0, 3, 12.1}, &Student{"关羽", 0, 6, 9.9}, &Student{"刘备", 1, 12, 0}, &Student{"诸葛亮", 1, 0, 1}, &Student{"曹操", 0, 1, 1000}, } // 使用sort包进行排序 sort.Slice(students, func(i, j int) bool { //先是否根据是否在线进行排序 if students[i].IsOnline != students[j].IsOnline { return students[i].IsOnline > students[j].IsOnline } //在通过积分进行排序 if students[i].Integral != students[j].Integral { return students[i].Integral > students[j].Integral } //最后通过金币排序 return students[i].Gold > students[j].Gold }) // 遍历英雄列表打印排序结果 for _, v := range students { fmt.Printf("%+v\n", v) } }

结果:

> go run test.go &{Name:吕布 IsOnline:1 Integral:12 Gold:11} &{Name:刘备 IsOnline:1 Integral:12 Gold:0} &{Name:诸葛亮 IsOnline:1 Integral:0 Gold:1} &{Name:关羽 IsOnline:0 Integral:6 Gold:9.9} &{Name:张飞 IsOnline:0 Integral:3 Gold:12.1} &{Name:曹操 IsOnline:0 Integral:1 Gold:1000}