google-app-engine - 如何在 GAE Go 中对 slice 进行排序

标签 google-app-engine sorting interface go slice

我正在尝试对 slice 进行排序。如何在 gae 中使用 go?

我有结构

type courseData struct {
  Key         *datastore.Key
    FormKey         *datastore.Key
  Selected    bool
  User        string
  Name        string
  Description string
  Date        time.Time
} 

我想在名称字段中对这种实体类型的 slice 进行排序。

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

我试过了

Sort(data Interface)

但不知道如何使用它。 请帮忙。谢谢!

最佳答案

例如,

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)
    } 

输出:

Jane
John
Peter

CourseCourses 需要导出以供 sort 包使用。

为避免使示例依赖于 GAE,类型 *datastore.Key 已更改为 string

关于google-app-engine - 如何在 GAE Go 中对 slice 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15700908/

相关文章:

javascript - 如何根据对象属性对数组中的对象键进行排序?

arrays - 我需要帮助根据字符串中的日期匹配对列进行动态排序

java - 向所有实现接口(interface)的类添加方法

google-app-engine - 为 Google App Engine 创建简单的搜索

google-app-engine - Google App Engine 错误未知任务队列

google-app-engine - Google App Engine 大型查询显示排名

Java 接口(interface)的对象实现

google-app-engine - 如何在与 app.yaml 不同的文件夹中为 appengine Go 使用主包?

c - 降序不能正常工作c编程

c++ - 与 Ruby 的 Rack 最接近的 C++ 类似物是什么?