GO语言学习日记:实现Sort接口

//实现Hero结构体切片的排序:sort.Sort(data Interface)
import (
	"fmt"
	"math/rand"
	"sort"
)

//1.首先声明一个结构体,叫Hero结构体
type Hero struct {
	Name string
	Age  int
}

//2.声明一个Hero结构体切片类型
type HeroSlice []Hero

//3.实现Interface接口
//Interface 表明需要实现的三个方法。

// 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)
// 	}

//1.Len
func (hs HeroSlice) Len() int {
	return len(hs)
}

//2.less	决定是使用什么标准来进行排序
func (hs HeroSlice) Less(i, j int) bool {
	return hs[i].Age > hs[j].Age
	//return hs[i].Name > hs[j].Name
}
//3.Swap
func (hs HeroSlice) Swap(i, j int) {
	hs[i], hs[j] = hs[j], hs[i]
}

type Student struct {
	Name  string
	Age   int
	Score float64
}

type StudentSlice []Student

//student的实现接口的三个函数
func (st StudentSlice) Len() int {
	return len(st)
}

//2.less	决定是使用什么标准来进行排序
func (st StudentSlice) Less(i, j int) bool {
	return st[i].Score > st[j].Score
	//return st[i].Name > st[j].Name
}

func (st StudentSlice) Swap(i, j int) {
	st[i], st[j] = st[j], st[i]
}

func main() {
	//先定义 一个数组/切片
	var intSlice = []int{-1, 0, 10, 90}
	sort.Ints(intSlice) //直接对切片进行排序,在其内部进行排序会直接影响到这个切片
	fmt.Println(intSlice)

	//基于通用性的考虑,使用系统提供的方法来对结构体进行排序
	var heroes HeroSlice
	for i := 0; i < 10; i++ {
		hero := Hero{
			Name: fmt.Sprintf("英雄~%d", rand.Intn(100)),
			Age:  rand.Intn(100),
		}
		heroes = append(heroes, hero)
	}

	//先看看排序前的顺序
	for _, v := range heroes {
		fmt.Println(v)
	}

	sort.Sort(heroes)
	//再看看排序后的顺序
	fmt.Println("-----------排序后的顺序-----------")
	for _, v := range heroes {
		fmt.Println(v)
	}

	//实现student的方式
	var st StudentSlice
	for i := 0; i < 10; i++ {
		smallst := Student{
			Name:  fmt.Sprintf("学生~%d", rand.Intn(100)),
			Age:   rand.Intn(100),
			Score: float64(rand.Intn(100)),
		}
		st = append(st, smallst)
	}

	//先看看排序前的顺序
	for _, v := range st {
		fmt.Println(v)
	}

	sort.Sort(st)
	//再看看排序后的顺序
	fmt.Println("-----------排序后的顺序-----------")
	for _, v := range st {
		fmt.Println(v)
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值