按日期对 GO 结构进行排序,该日期通过 proto 消息定义

我在原始文件中定义了一条消息:


my.proto

--------

message Holiday {

  string title = 1;

  google.protobuf.Timestamp date = 2;

}

编译后,它会创建 my.pb.go


现在在我的 go 代码中,我有一个 Holiday 的片段。


main.go

-------

holidays := []my.Holiday{...}

我必须按Holiday.date对此切片进行排序。根据文档,如果我想使用排序进行排序。排序然后我必须实现Len,Swap&Less方法。但是我无法在我的 go 代码中定义这些接收器方法,因为它来自不同的包 (my.pb.go)。有没有办法解决这个问题?Holiday


翻过高山走不出你
浏览 124回答 3
3回答

忽然笑

你可以只使用排序。切片,不需要实现 。sort.InterfaceSlice 在给定提供的 less 函数的情况下对切片 x 进行排序。如果 x 不是切片,则会惊慌失措。sort.Slice(holidays, func(i, j int) bool {    return holidays[i].GetDate().Before(holidays[j].GetDate())  })

交互式爱情

排序包文档显示了回答问题的两个示例。第一个包示例使用所需的方法声明切片类型:type Person struct {&nbsp; &nbsp; Name string&nbsp; &nbsp; Age&nbsp; int}type ByAge []Personfunc (a ByAge) Len() int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ return len(a) }func (a ByAge) Swap(i, j int)&nbsp; &nbsp; &nbsp; { 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 目的定义类型。

catspeake

排序中的示例。排序文档演示如何通过使用即席结构来实现此目的:SortKeys// A Planet defines the properties of a solar system object.type Planet struct {&nbsp; &nbsp; name&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; mass&nbsp; &nbsp; &nbsp;earthMass&nbsp; &nbsp; 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) {&nbsp; &nbsp; ps := &planetSorter{&nbsp; &nbsp; &nbsp; &nbsp; planets: planets,&nbsp; &nbsp; &nbsp; &nbsp; by:&nbsp; &nbsp; &nbsp; by, // The Sort method's receiver is the function (closure) that defines the sort order.&nbsp; &nbsp; }&nbsp; &nbsp; sort.Sort(ps)}// planetSorter joins a By function and a slice of Planets to be sorted.type planetSorter struct {&nbsp; &nbsp; planets []Planet&nbsp; &nbsp; by&nbsp; &nbsp; &nbsp; func(p1, p2 *Planet) bool // Closure used in the Less method.}// Len is part of sort.Interface.func (s *planetSorter) Len() int {&nbsp; &nbsp; return len(s.planets)}// Swap is part of sort.Interface.func (s *planetSorter) Swap(i, j int) {&nbsp; &nbsp; 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 {&nbsp; &nbsp; return s.by(&s.planets[i], &s.planets[j])}鉴于只接受 一个,它不关心你正在使用什么数据结构或你实际交换的类型。sort.Sortsort.Interface
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go