Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go sort slice of pointers

Tags:

go

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?

like image 968
nickbusted Avatar asked Mar 14 '23 08:03

nickbusted


1 Answers

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.

like image 106
Not_a_Golfer Avatar answered Mar 24 '23 22:03

Not_a_Golfer