对自定义类型「struct」列表排序

61 阅读1分钟
对自定义类型「struct」列表排序

通过实现sort.Interface接口来自定义类型的排序行为。sort.Interface接口定义了三个方法:Len()Less(i, j int) boolSwap(i, j int)

要自定义类型列表的排序顺序,你需要创建一个新的类型,并为其实现sort.Interface接口的方法。


type CostComparisonOverview []AliyunCostComparisonOverviewResponse

// 实现sort.Interface接口的Len方法
func (list CostComparisonOverview) Len() int {
	return len(list)
}

// 实现sort.Interface接口的Less方法
func (list CostComparisonOverview) Less(i, j int) bool {
	return list[i].ProductCode > list[j].ProductCode
}

// 实现sort.Interface接口的Swap方法
func (list CostComparisonOverview) Swap(i, j int) {
	list[i], list[j] = list[j], list[i]
}



// 对列表进行排序
var list CostComparisonOverview
list = overview.Record
sort.Sort(list)
                

排序,可解决在协程等特定场景下,需要保证通过列表下标访问列表时,结果一致的情况。