gosort
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
LessTime
如下是一个Demo,按照人的年龄来排序。
package main
import (
"fmt"
"sort"
)
// Person struct
type Person struct {
Name string
Age int
}
// Persons a set of person
type Persons []Person
// Len return count
func (p Persons) Len() int {
return len(p)
}
// Less return bigger true
func (p Persons) Less(i, j int) bool {
return p[i].Age < p[j].Age
}
// Swap swap items
func (p Persons) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func main() {
ps := Persons{}
ps = append(ps, Person{
"张三", 31,
})
ps = append(ps, Person{
"李四", 23,
})
ps = append(ps, Person{
"王五", 40,
})
sort.Sort(ps)
fmt.Println(ps)
}