繁体   English   中英

去排序指针

[英]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]
}

在main方法中,我有一段指向Item的指针,必须对它进行排序。 我的尝试是:

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
}

虽然它做了我需要的,还有另一种方法吗?

只需将Items项目指针列表:

type Items []*Item

它可以使用您已经描述过的方法进行排序。 而已。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM