golang接口简单应用
package main import ( "fmt" "math/rand" "sort" ) //Hero结构体 type Hero struct { Name string Age int } //Hero结构体切片 type HeroSlice []Hero //实现interface接口 func (hs HeroSlice) Len() int { return len(hs) } //Less方法就是决定使用什么标准进行排序 //按Hero年龄从小到大排序 func (hs HeroSlice) Less(i, j int) bool { return hs[i].Age < hs[j].Age } func (hs HeroSlice) Swap(i, j int) { //完成交换 temp := hs[i] hs[i] = hs[j] hs[j] = temp //hs[i], hs[j] = hs[j], hs[i] } func main() { var heroes HeroSlice for i := 0; i < 10; i++ { hero := Hero{ Name: fmt.Sprintf("英雄%d", rand.Intn(100)), Age: rand.Intn(100), } //将hero append到heroes切片 heroes = append(heroes, hero) } fmt.Println("排序前的顺序") for _, v := range heroes { fmt.Println(v) } //调用sort.Sort sort.Sort(heroes) fmt.Println("排序后的顺序") for _, v := range heroes { fmt.Println(v) } }