package main
import ( "fmt" "sort" )
type Student struct { name string age int }
func (s *Student) String() string { return fmt.Sprintf("(%s, %d)", s.name, s.age) }
type StudentSlice []*Student
func (list StudentSlice) Len() int { return len(list) }
func (list StudentSlice) Less(i, j int) bool { if list[i].age < list[j].age { return true } else if list[i].age > list[j].age { return false } else { return list[i].name < list[j].name } }
func (list StudentSlice) Swap(i, j int) { list[i], list[j] = list[j], list[i] }
func main() { a := []int{1, 2, 9, 0, 5, 7, 6, 3, 4, 8} sort.Sort(sort.IntSlice(a)) fmt.Println(a)
b := []float64{1.1, 2.2, 3.4, 2.8, 1.2, 4.5, -6.1, -0.6, -4.0, 2.4} sort.Sort(sort.Float64Slice(b)) fmt.Println(b)
c := []string{"f", "c", "d", "b", "a", "z", "x", "y"} sort.Sort(sort.StringSlice(c)) fmt.Println(c)
s := StudentSlice([]*Student{ &Student{"f", 18}, &Student{"c", 17}, &Student{"d", 19}, &Student{"b", 16}, &Student{"a", 15}, &Student{"z", 18}, &Student{"x", 18}, &Student{"y", 17}, }) sort.Sort(s) fmt.Println(s) }
|