Go 自定义结构体切片排序

实现 sort 包下接口的三个方法的结构体可以调用方法进行排序
Len() int
Less(i, j int) bool
Swap(i, j int)

// Package sort provides primitives for sorting slices and user-defined
// collections.
package sort

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
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)
}

举个例子:

package main

import (
	"fmt"
	"math/rand"
	"sort"
)

//声明Hero结构体
type Hero struct {
	Name string
	Age  int
}

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

//切片实现Interface 接口的三个方法
//1.Len() :返回切片的大小
func (hs HeroSlice) Len() int {
	return len(hs)
}

//2.Less(i, j int) :决定使用什么规则进行排序
func (hs HeroSlice) Less(i, j int) bool {
	return hs[i].Age < hs[j].Age      // 按Hero的Age从小到大排序
	//return hs[i].Name > hs[j].Name  // 按Hero的Name从大到小排序
}

//3.Swap(i, j int) :Less(i, j int)返回true时进行交换
func (hs HeroSlice) Swap(i, j int) {
	hs[i], hs[j] = hs[j], hs[i]
}

func main() {
	//----------------------------- 基本类型切片排序 -------------------------------
	var intSlice = []int{0, -1, 10, 7, 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)
	}

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

	//结构体实现了排序Interface接口,可以调用sort.Sort进行结构体排序
	sort.Sort(heroes)

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

}

运行结果:

[-1 0 7 10 90]
-----------排序前------------
{英雄81 87}
{英雄47 59}
{英雄81 18}
{英雄25 40}
{英雄56 0}
{英雄94 11}
{英雄62 89}
{英雄28 74}
{英雄11 45}
{英雄37 6}
-----------排序后------------
{英雄56 0}
{英雄37 6}
{英雄94 11}
{英雄81 18}
{英雄25 40}
{英雄11 45}
{英雄47 59}
{英雄28 74}
{英雄81 87}
{英雄62 89}

Process finished with exit code 0

想要学习更多Go语言语法和Go语言在工作中的常用知识点可以参考我的笔记源码 https://github.com/qiuyunzhao/go_basis

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值