I am trying to sort slices. How to this in gae using go?
I have struct
type courseData struct {
Key *datastore.Key
FormKey *datastore.Key
Selected bool
User string
Name string
Description string
Date time.Time
}
I would like to sort slice of this entity kind in the Name field.
q := datastore.NewQuery("Course")
var courses []*courseData
if keys, err := q.GetAll(c, &courses); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
for i := range courses {
courses[i].Key = keys[i]
}
}
I tried the
Sort(data Interface)
but not sure how to use it. Please help. Thanks!
For example,
package main
import (
"fmt"
"sort"
"time"
)
type Course struct {
Key string // *datastore.Key
FormKey string // *datastore.Key
Selected bool
User string
Name string
Description string
Date time.Time
}
type Courses []*Course
func (s Courses) Len() int { return len(s) }
func (s Courses) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type ByName struct{ Courses }
func (s ByName) Less(i, j int) bool { return s.Courses[i].Name < s.Courses[j].Name }
func main() {
var courses = Courses{
&Course{Name: "John"},
&Course{Name: "Peter"},
&Course{Name: "Jane"},
}
sort.Sort(ByName{courses})
for _, course := range courses {
fmt.Println(course.Name)
}
Output:
Jane
John
Peter
Course
and Courses
need to be exported for use by the sort
package.
To avoid making the example dependent on GAE, type *datastore.Key
was changed to string
.
Why not just ask for the entities in the correct order from the datastore?
q := datastore.NewQuery("Course").Order("Name")