代码改变世界

go 学习之接口实例(自定义类型排序)

2020-12-15 09:46  Caoxt  阅读(100)  评论(0编辑  收藏  举报

按年龄排序

package main

import (
        "fmt"
        "sort"
)

type Person struct {
        name string
        age int
        score float64
}

type PersonSlice []Person

func (p PersonSlice) Len() int {
        return len(p)
}

func (p PersonSlice) Less(i, j int) bool {
        return p[i].age < p[j].age
}

func (p PersonSlice) Swap(i, j int) {
        p[i], p[j] = p[j], p[i]
}

func main() {
        p1 := Person{"caoxt", 29, 60.00}
        p2 := Person{"caoxt4", 40, 90.00}
        p3 := Person{"caoxt6", 23, 80.00}
        p4 := Person{"caoxt2", 24, 70.00}

        var persons PersonSlice
        persons = append(persons,p1,p2,p3,p4)
        sort.Sort(PersonSlice(persons))
        fmt.Println(persons)

}