对象切片排序
在Go语言中,对对象切片进行排序的基本步骤如下:
- 定义对象类型
- 实现sort.Interface接口
- 实现Less方法,该方法定义了对象的比较规则
- 使用sort包中的sort方法,进行排序
举例:
package main
import (
"fmt"
"sort"
)
type Employee struct {
Name string
Age int
}
type Employees []Employee
func (s Employees) Len() int {
return len(s)
}
func (s Employees) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s Employees) Less(i, j int) bool {
return s[i].Age < s[j].Age
}
func main() {
staffs := []Employee{
{Name: "Peter", Age: 18},
{Name: "Mike", Age: 20},
{Name: "Rose", Age: 12},
{Name: "Jake", Age: 14},
{Name: "Bill", Age: 10},
}
sort.Sort(Employees(staffs))
for i := range staffs {
fmt.Println(staffs[i].Name, staffs[i].Age)
}
}
运行结果:
Bill 10
Rose 12
Jake 14
Peter 18
Mike 20
按照员工的年龄从小到大对员工列表进行排序输出。
map根据值进行排序
在Go语言中,map是无序的,因此不能直接对map的值进行排序。可以将map中的值提取出来,转化为切片,然后针对切片进行排序。具体实现步骤如下:
- 从map中提取所有值放到切片中。
- 实现一个sort.Interface接口的类型,该类型代表一个map值所具有的的属性
- 使用sort.Sort方法,根据Person实现的排序规则对切片进行排序。
举例:
type Person struct {
Name string
Age int
}
type ByAge []Person
func (a ByAge) Len() int {
return len(a)
}
func (a ByAge) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByAge) Less(i, j int) bool {
return a[i].Age < a[j].Age
}
func main() {
ages := map[string]int{
"Peter": 18,
"Mike": 20,
"Rose": 12,
"Jake": 14,
"Bill": 10,
}
people := make([]Person, len(ages))
i := 0
for k, v := range ages {
people[i] = Person{k, v}
i++
}
sort.Sort(ByAge(people))
for _, person := range people {
fmt.Printf("%s\t%d\n", person.Name, person.Age)
}
}
运行结果:
Bill 10
Rose 12
Jake 14
Peter 18
Mike 20
按照人员的年龄从小到大对map的值进行排序输出。