问题描述
我有一个成员数组/切片:
I have an array/slice of members:
type Member struct {
Id int
LastName string
FirstName string
}
var members []Member
我的问题是如何按LastName
然后按FirstName
对其进行排序.
My question is how to sort them by LastName
and then by FirstName
.
推荐答案
使用 sort.Slice (从Go 1.8开始可用)或 sort.Sort 函数对值的一部分进行排序.
Use the sort.Slice (available since Go 1.8) or the sort.Sort function to sort a slice of values.
使用这两个功能,应用程序都提供了一个功能,用于测试一个slice元素是否小于另一个slice元素.要按姓氏和名字排序,请比较姓氏和名字:
With both functions, the application provides a function that tests if one slice element is less than another slice element. To sort by last name and then first name, compare last name and then first name:
if members[i].LastName < members[j].LastName {
return true
}
if members[i].LastName > members[j].LastName {
return false
}
return members[i].FirstName < members[j].FirstName
less函数是使用带有sort.Slice的匿名函数指定的:
The less function is specified using an anonymous function with sort.Slice:
var members []Member
sort.Slice(members, func(i, j int) bool {
if members[i].LastName < members[j].LastName {
return true
}
if members[i].LastName > members[j].LastName {
return false
}
return members[i].FirstName < members[j].FirstName
})
less函数通过带有sort.Sort函数的接口指定:
The less function is specified with through an interface with the sort.Sort function:
type byLastFirst []Member
func (members byLastFirst) Len() int { return len(members) }
func (members byLastFirst) Swap(i, j int) { members[i], members[j] = members[j], members[i] }
func (members byLastFirst) Less(i, j int) bool {
if members[i].LastName < members[j].LastName {
return true
}
if members[i].LastName > members[j].LastName {
return false
}
return members[i].FirstName < members[j].FirstName
}
sort.Sort(byLastFirst(members))
除非性能分析表明排序是一个热点,否则请使用最适合您的应用程序的功能.
Unless performance analysis shows that sorting is a hot spot, use the function that's most convenient for your application.
这篇关于如何使用多个排序参数对结构进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!