golang slice 排序

如下示例为,在一个Person切片中,按年龄大小进行排序

package main

import (
    "fmt"
    "sort"
)

/*slice 排序示例*/
type Person struct {
    Age int
}

type PersonSlice []Person

func (s PersonSlice) Len() int           { return len(s) }
func (s PersonSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s PersonSlice) Less(i, j int) bool { return s[i].Age < s[j].Age }

func main() {
    persons := PersonSlice{
        Person{
            Age: 1,
        },
        Person{
            Age: 5,
        },
        Person{
            Age: 2,
        },
    }
    sort.Sort(persons)
    fmt.Printf("after sort:%+v", persons)
}

输出 after sort:[{Age:1} {Age:2} {Age:5}]

说明:被排序的结构体需要实现如下接口

type Interface interface {
    // 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)
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,064评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,985评论 18 399
  • 一、目标管理中职工参与体现在哪些方面? 目标管理是员工参与管理的一种形式,体现在目标管理的全过程中。 1.员工参与...
    阿飞fighting阅读 1,738评论 0 0
  • 大帅拳霸阅读 1,459评论 0 0
  • 01 八月二号的早上九点多钟,我住院了。我是好手脚好走进病房里,也希望能有惊无险地出院。一进...
    Sonia岚阅读 3,544评论 5 12

友情链接更多精彩内容