Go语言使用sort包对任意类型元素的集合进行排序的方法
本文实例讲述了Go语言使用sort包对任意类型元素的集合进行排序的方法。分享给大家供大家参考。具体如下:
使用sort包的函数进行排序时,集合需要实现sort.Inteface接口,该接口中有三个方法:
//Lenisthenumberofelementsinthecollection. Len()int //Lessreportswhethertheelementwith //indexishouldsortbeforetheelementwithindexj. Less(i,jint)bool //Swapswapstheelementswithindexesiandj. Swap(i,jint)
以下为简单示例:
//对任意对象进行排序
typePersonstruct{
namestring
age int
}
//为*Person添加String()方法,便于输出
func(p*Person)String()string{
returnfmt.Sprintf("(%s,%d)",p.name,p.age)
}
typePersonList[]*Person
//排序规则:首先按年龄排序(由小到大),年龄相同时按姓名进行排序(按字符串的自然顺序)
func(listPersonList)Len()int{
returnlen(list)
}
func(listPersonList)Less(i,jint)bool{
iflist[i].age<list[j].age{
returntrue
}elseiflist[i].age>list[j].age{
returnfalse
}else{
returnlist[i].name<list[j].name
}
}
func(listPersonList)Swap(i,jint){
vartemp*Person=list[i]
list[i]=list[j]
list[j]=temp
}
funcinterfaceTest0203(){
fmt.Println("------")
p1:=&Person{"Tom",19}
p2:=&Person{"Hanks",19}
p3:=&Person{"Amy",19}
p4:=&Person{"Tom",20}
p5:=&Person{"Jogn",21}
p6:=&Person{"Mike",23}
pList:=PersonList([]*Person{p1,p2,p3,p4,p5,p6})
sort.Sort(pList)
fmt.Println(pList)
/*output:
[(Amy,19)(Hanks,19)(Tom,19)(Tom,20)(Jogn,21)(Mike,23)]*/
}
希望本文所述对大家的Go语言程序设计有所帮助。