我正在尝试映射 query.GetAll() 检索到的结果
我需要映射结果,因为模板需要与每个实体关联的数据存储“ key ”。
目前我正在做以下事情:
// Query
q := datastore.NewQuery("Article").Limit(10)
// Define array where the entities will be retreived
var a[] Article;
// Retreive entities
key, _ := q.GetAll(c, &a)
// Create an empty map
article := map[string] Article{}
// Build the map
for k := range a {
article[key[k].Encode()] = a[k];
}
template.Execute(w, map[string]interface{} { "Articles" : article})
是否有更有效的方法直接使用 query.GetAll() 构建 map ,因为创建一个数组、一个 map 并在数组上循环构建 map 似乎并不明智?
或者获取与每个实体关联的数据存储 key (已编码)的更有效方法?
最佳答案
也许最好的办法是将 slice 压缩成一个 slice 。沿着这些思路,
package main
import (
"os"
"text/template"
)
type pair struct {
Key string
Article string
}
var tmpt = `Here's the list:{{range $p := .}}
{{$p.Key}}: {{$p.Article}}{{end}}
`
func main() {
list := template.Must(template.New("list").Parse(tmpt))
// query
key := []string{"banana", "donkey", "curious"}
a := []string{"long fruit", "who needs one?", "human nature"}
// zip
pairs := make([]pair, len(key))
for i, k := range key {
pairs[i].Key = k
pairs[i].Article = a[i]
}
// execute on zipped list
if err := list.Execute(os.Stdout, pairs); err != nil {
os.Stdout.WriteString(err.Error())
}
}
输出:
Here's the list: banana: long fruit donkey: who needs one? curious: human nature
关于google-app-engine - Appengine > Go > 映射数据存储结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10377121/