对切片指针进行排序

huangapple go评论78阅读模式
英文:

Go sort slice of pointers

问题

考虑以下代码的翻译:

type Item struct {
    Title string
    Date  time.Time
}

type Items []Item

func (slice Items) Len() int {
    return len(slice)
}

func (slice Items) Less(i, j int) bool {
    return slice[i].Date.After(slice[j].Date)
}

func (slice Items) Swap(i, j int) {
    slice[i], slice[j] = slice[j], slice[i]
}

在主方法中,我有一个指向Item的指针切片,需要对其进行排序。我的尝试是:

items := make(Items, len(in.Items)) // in.Items 的类型为 []*Item
for i, value := range in.Items {
    items[i] = *value
}

sort.Sort(items)

in.Items = make([]*Item, len(items))
for i, value := range items {
    in.Items[i] = &value
}

虽然这样做可以达到我想要的效果,但还有其他方法可以实现吗?

英文:

Consider the following:

type Item struct {
	Title      string
	Date       time.Time
}  

type Items []Item

func (slice Items) Len() int {
	return len(slice)
}

func (slice Items) Less(i, j int) bool {
	return slice[i].Date.After(slice[j].Date)
}

func (slice Items) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

In the main method, I have a slice of pointers to Item, that must be sorted. My attempt is:

items := make(Items, len(in.Items)) //in.Items is of type []*Item
for i, value := range in.Items {
	items[i] = *value
}

sort.Sort(items)

in.Items = make([]*Item, len(items))
for i, value := range items {
	in.Items[i] = &value
}

While it does what I need, is there another way to do this?

答案1

得分: 8

只需将Items定义为一个项目指针的列表:

type Items []*Item

然后,您可以使用您已经描述的方法对其进行排序。就是这样。

英文:

Just make Items a list of item pointers:

type Items []*Item

and it can be sorted with the methods you've already described. that's it.

huangapple
  • 本文由 发表于 2016年2月7日 19:26:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/35252880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定