本文实例讲述了Go语言使用sort包对任意类型元素的集合进行排序的方法。分享给大家供大家参考。具体如下:
使用sort包的函数进行排序时,集合需要实现sort.Inteface接口,该接口中有三个方法:
复制代码 代码如下:
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
以下为简单示例:
复制代码 代码如下:
//对任意对象进行排序
type Person struct {
name string
age int
}
//为*Person添加String()方法,便于输出
func (p *Person) String() string {
return fmt.Sprintf("( %s,%d )", p.name, p.age)
}
type PersonList []*Person
//排序规则:首先按年龄排序(由小到大),年龄相同时按姓名进行排序(按字符串的自然顺序)
func (list PersonList) Len() int {
return len(list)
}
func (list PersonList) Less(i, j int) bool {
if list[i].age < list[j].age {
return true
} else if list[i].age > list[j].age {
return false
} else {
return list[i].name < list[j].name
}
}
func (list PersonList) Swap(i, j int) {
var temp *Person = list[i]
list[i] = list[j]
list[j] = temp
}
func interfaceTest0203() {
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 )] */
}
type Person struct {
name string
age int
}
//为*Person添加String()方法,便于输出
func (p *Person) String() string {
return fmt.Sprintf("( %s,%d )", p.name, p.age)
}
type PersonList []*Person
//排序规则:首先按年龄排序(由小到大),年龄相同时按姓名进行排序(按字符串的自然顺序)
func (list PersonList) Len() int {
return len(list)
}
func (list PersonList) Less(i, j int) bool {
if list[i].age < list[j].age {
return true
} else if list[i].age > list[j].age {
return false
} else {
return list[i].name < list[j].name
}
}
func (list PersonList) Swap(i, j int) {
var temp *Person = list[i]
list[i] = list[j]
list[j] = temp
}
func interfaceTest0203() {
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语言程序设计有所帮助。