为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
翻过高山走不出你 2022-08-24 20:26:46
我在原始文件中定义了一条消息: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
查看完整描述

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())  

})


查看完整回答
反对 回复 2022-08-24
?
交互式爱情

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 目的定义类型。


查看完整回答
反对 回复 2022-08-24
?
catspeake

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


查看完整回答
反对 回复 2022-08-24
  • 3 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号