[Golang] 实现一个通用的排序方式(对任意数据类型构成的slice排序)

本文介绍了一种在Go语言中对复杂类型结构体组成的切片进行排序的通用方法,通过定义一个包含任意结构体切片的Bucket结构体,并实现Len, Swap, Less三个方法,仅需定义排序规则函数即可对不同结构体切片进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:

Go 语言中排序主要使用的sort库,对于常见数据类型string, int ,float构成的Slice,可以使用sort库对应的sort.Strings() / sort.Ints() / sort.Float64s()直接排序,但是对于复杂类型struct构成的Slice,要对其排序就需要自己实现其三个方法(Len, Swap,Less)。

问题在于:一个结构体我可以给他写三个方法,那10个结构体我得写30个方法?

这一定是不合理的,办法总比困难多,本文结合 【WangC.W】-- go语言的排序、结构体排序 一文以及自己的理解实现了一套通用的golang排序写法。

正文:

package main

import (
	"fmt"
	"sort"
)

//待排序的结构体
type City struct {
	Name 	string
	Number 	int
	Test 	bool
}

//待排序的结构体
type Animal struct {
	Name 	string    // 名字
	Height  float32    // 高度
	Weight 	float32  //体重
}

//定义一个通用的结构体
type Bucket struct {
	Slice []interface{}  //承载以任意结构体为元素构成的Slice
	By func(a,b interface{})bool  //排序规则函数,当需要对新的结构体slice进行排序时,只需定义这个函数即可
}
/*
定义三个必须方法的准则:接收者不能为指针
*/
func (this Bucket)Len()int { return len(this.Slice)}

func (this Bucket)Swap(i,j int){ this.Slice[i],this.Slice[j] = this.Slice[j],this.Slice[i] }

func (this Bucket)Less(i,j int)bool { return this.By(this.Slice[i], this.Slice[j]) }


func main() {
    
    //对第一个结构体排序
	c1 := City{"Los Angeles",1024, true}
	c2 := City{"Wellington",128,false}
	c3 := City{"Seattle",64,false}

	//定义专属的排序函数
	city_by := func(a,b interface{})bool {
		return a.(City).Number > b.(City).Number   //按年龄排倒序
	}
	citys := Bucket{}
	citys.Slice = append(citys.Slice, c1,c2,c3)
	citys.By = city_by
	sort.Sort(citys)
	fmt.Printf("%+v\n", citys.Slice)


	/***************对第二个结构体排序*****************/
	a1 := Animal{"pigeon",0.15,3}
	a2 := Animal{"sheep",1,20}
	a3 := Animal{"giraffe",3,70}

	//定义结构体Animal的专属排序函数 -- 关键代码
	animal_by := func(a,b interface{})bool {
		return a.(Animal).Weight > b.(Animal).Weight  //按体重排倒序
	}
	animals := Bucket{}
	animals.Slice = append(animals.Slice, a1,a2,a3)
	animals.By = animal_by // -- 关键代码
	sort.Sort(animals) // -- 关键代码
	fmt.Printf("%+v\n", animals.Slice) //已排序的slice
}

再次感谢【WangC.W】-- go语言的排序、结构体排序 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值