2,348
社区成员




import "sort"
type user struct {
id int
name string
}
type users []user
func (u users) Len() int {
return len(u)
}
func (u users) Less(i, j int) bool {
if u[i].id == u[j].id {
return u[i].name < u[j].name
}
return u[i].id < u[j].id//sort by id if id is the same sort by name...
}
func (u users) Swap(i ,j int) {
u[i].id, u[j].id = u[j].id, u[i].id
u[i].name, u[j].name = u[j].name, u[i].name
}
uu := []user{{1,"aa"}, {20,"bb"}, {3, "cc"}, {3, "cb"}}
fmt.Println(uu)
sort.Sort(users(uu))
fmt.Println(uu)
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%s: %d", p.Name, p.Age)
}
// ByAge implements sort.Interface for []Person based on
// the Age field.
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() {
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
fmt.Println(people)
sort.Sort(ByAge(people))
fmt.Println(people)
}
golang官方实例