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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With