考虑以下:
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]
}
Run Code Online (Sandbox Code Playgroud)
在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
}
Run Code Online (Sandbox Code Playgroud)
虽然它做了我需要的,还有另一种方法吗?