开发中难免需要根据Struct的某一属性对该Struct的Slice进行自定义排序,下面介绍一下具体的实现方法
- 首先定义一个待排序的Struct,假设对
Label
属性进行排序
type ER struct {
Id string `json:"id"`
Label string `json:"label"`
Main bool `json:"main"`
Icon string `json:"icon"`
}
- 排序之前需要先定义一个该Struct的Slice类型,并实现三个方法
type ERs []*ER
- 实现三个方法,分别是
Len
、Swap
和Less
Len方法用于计算长度
Swap方法用于交换
Less用于定义比较规则
func (e ERs) Len() int {
return len(e)
}
func (e ERs) Swap(i, j int) {
e[i], e[j] = e[j], e[i]
}
func (e ERs) Less(i, j int) bool {
return e[i].Label > e[j].Label
}
注意:Less方法中 使用大于号
>
表示降序,小于号<
表示升序
可以任意定义比较规则!~
- 下面就可以使用该排序规则了,代码如下
- 准备一个Slice
ers := []*ER{}
ers = ers.append(ers, &ER{Id:1, Label:"label", Main:false, Icon:"dim"})
ers = ers.append(ers, &ER{Id:2, Label:"lebal", Main:false, Icon:"dim"})
ers = ers.append(ers, &ER{Id:2, Label:"laleb", Main:false, Icon:"dim"})
- 调用排序方法
sort.Sort(ERs(ers))
其中:
sort.Sort()
为方法
ERs
为刚刚定义的待排序Struct的Slice 类型
ers
为待排序的Slice
- 完成排序