3 回答
TA贡献1806条经验 获得超5个赞
你可以只使用排序。切片,不需要实现 。sort.Interface
Slice 在给定提供的 less 函数的情况下对切片 x 进行排序。如果 x 不是切片,则会惊慌失措。
sort.Slice(holidays, func(i, j int) bool {
return holidays[i].GetDate().Before(holidays[j].GetDate())
})
TA贡献1712条经验 获得超3个赞
排序包文档显示了回答问题的两个示例。
第一个包示例使用所需的方法声明切片类型:
type Person struct {
Name string
Age int
}
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
...
sort.Sort(ByAge(people))
请注意,Len、Swap 和 Less 方法位于为排序而定义的片类型上,而不是结构类型上。您可以在自己的包中定义该类型。
排序。Slice 示例显示如何仅使用较少的函数进行排序:
sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
在此示例中,无需为 soring 目的定义类型。
TA贡献1111条经验 获得超0个赞
排序中的示例。排序文档演示如何通过使用即席结构来实现此目的:SortKeys
// A Planet defines the properties of a solar system object.
type Planet struct {
name string
mass earthMass
distance au
}
// By is the type of a "less" function that defines the ordering of its Planet arguments.
type By func(p1, p2 *Planet) bool
// Sort is a method on the function type, By, that sorts the argument slice according to the function.
func (by By) Sort(planets []Planet) {
ps := &planetSorter{
planets: planets,
by: by, // The Sort method's receiver is the function (closure) that defines the sort order.
}
sort.Sort(ps)
}
// planetSorter joins a By function and a slice of Planets to be sorted.
type planetSorter struct {
planets []Planet
by func(p1, p2 *Planet) bool // Closure used in the Less method.
}
// Len is part of sort.Interface.
func (s *planetSorter) Len() int {
return len(s.planets)
}
// Swap is part of sort.Interface.
func (s *planetSorter) Swap(i, j int) {
s.planets[i], s.planets[j] = s.planets[j], s.planets[i]
}
// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
func (s *planetSorter) Less(i, j int) bool {
return s.by(&s.planets[i], &s.planets[j])
}
鉴于只接受 一个,它不关心你正在使用什么数据结构或你实际交换的类型。sort.Sortsort.Interface
- 3 回答
- 0 关注
- 123 浏览
添加回答
举报
