golang struct 排序

1,写个要排序的结构体

type xyz struct {

  1...

   2...

}

2,写个上面结构的数组结构

type xyzlist []xyz

3,重写三个方法

func (a xyzlist) Len() int {    	 // 重写 Len() 方法
    return len(a)
}
func (a xyzlist) Swap(i, j int){     // 重写 Swap() 方法
    a[i], a[j] = a[j], a[i]
}
func (a xyzlist) Less(i, j int) bool {    // 重写 Less() 方法, 从大到小排序
    return a[j].Age < a[i].Age
}

4,执行排序:

xyzaaa := []xyz{

   1...

   a...

   2...

}

sort.Sort(xyzlist(xyzaaa))

5, 收工。

发布了1295 篇原创文章 · 获赞 170 · 访问量 398万+

猜你喜欢

转载自blog.csdn.net/wide288/article/details/103744411