结构体定义
type A struct {
xx int,
yy int,
zz int,
}
重写排序方法
type Wrapper struct {
a []*A
by func(p, q *A) bool
}
type SortBy func(p, q *A) bool
func (pw Wrapper) Len() int {
return len(pw.a)
}
func (pw Wrapper) Swap(i, j int) {
pw.a[i], pw.a[j] = pw.a[j], pw.a[i]
}
func (pw Wrapper) Less(i, j int) bool {
return pw.by(pw.a[i], pw.a[j])
}
自定义规则
func GetSortByAA(a []*Topics) []*A {
sort.Sort(Wrapper{a, func(p, q *A) bool {
if p.yy > q.yy {
return true
} else {
if p.ww == q.ww {
if p.xx < q.xx {
return true
} else if p.xx == q.xx {
return p.zz > q.zz
} else {
return false
}
} else {
return false
}
}
}})
return topics
}
func GetSortByAAAA(result []*A) []*A {
sort.Sort(Wrapper{result, func(p, q *A) bool {
if p.xx > q.xx {
return true
} else {
if p.xx == q.xx {
if p.yy < q.yy {
return true
} else {
if p.zz == q.zz {
return p.UpdateAt.After(q.UpdateAt)
}
}
} else {
return false
}
}
return false
}})
return result
}
使用方法
var a = make([]*A, 0,10)
GetSortByArticleCount(a)