douqi1625 2019-05-28 13:01
浏览 85

如何对地图进行反向排序并将其发送到Go lang中的模型

I want to send a reverse order of a list of books that are stored in a map and send this to a model instead of the map in its current order.

I need to display a list in reverse order of date entered which is pubDate so that the webpage (model) displays the most recently added books instead of the books added first.

I have tried many various sort methods listed but I do not know how I would send this to the model. For example, I tried import "sort"

var m map[int]string
var keys []int
for k := range m {
    keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
    fmt.Println("Key:", k, "Value:", m[k])
}

I also tried sort.Slice(ad, func(i, j int) bool {

    return ad[i].date.Before(ad[j].date)})

there are many others but I can not seem to get any working.

type Book struct {
    ID     int64  `json:"id"`
    Title  string `json:"title"`
    Author string `json:"author"`
    pubDate time.Time `json:"pubDate"`
}

var bookModels = map[string]*Book{}

s := res.NewService("library")

    // Add handlers for "library.book.$id" models
    s.Handle(
        "book.$id",
        res.Access(res.AccessGranted),
        res.GetModel(getBookHandler),
        res.Set(setBookHandler),
    )

    // Add handlers for "library.books" collection
    s.Handle(
        "books",
        res.Access(res.AccessGranted),
        res.GetCollection(getBooksHandler),
        res.New(newBookHandler),
        res.Call("delete", deleteBookHandler),
    )

func getBookHandler(r res.ModelRequest) {

    book := bookModels[r.ResourceName()]
    if book == nil {
        r.NotFound()
        return
    }
    r.Model(book)
}

Mainly I get errors that the map does not allow indexing, or the wrong type, or cant access the fields, etc... How can you use a map and send it to a model and ensure that you have the most recent items listed first on the web page?

  • 写回答

2条回答 默认 最新

  • doulieyu0881 2019-05-28 13:10
    关注

    maps in go are always returned in a random order unless you use a key to access a value. so you can not reverse the order of a map because there is no order in the first place

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?