使用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)
以下为简单示例:
//对任意对象进行排序 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 )] */ }
有疑问加站长微信联系(非本文作者)
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)