英文:
GetAll: keys and entities guaranteed to be in same order?
问题
我一直在使用这个来加载实体,并且仍然可以使用键:
type Post struct {
Title string
Created time.Time
// ...
key *datastore.Key
}
func All(c appengine.Context) (*[]Post, error) {
var p []Post
q := datastore.NewQuery("Post").Order("-Created")
k, err := q.GetAll(c, &p)
if err != nil {
return nil, err
}
for i := 0; i < len(p); i++ {
p[i].key = k[i]
}
return &p, nil
}
然后我想知道是否可以始终相信 k
的顺序与 p
的顺序相同(即,k[0]
总是 p[0]
的键)?如果我理解正确的话,appengine-go源代码表明应该是这样的,因为两个切片都是使用append构建的。它似乎确实起作用。
我所做的是否安全?有更好的方法吗?
英文:
I've been using this to load entities and still have the keys available:
type Post struct {
Title string
Created time.Time
// ...
key *datastore.Key
}
func All(c appengine.Context) (*[]Post, error) {
var p []Post
q := datastore.NewQuery("Post").Order("-Created")
k, err := q.GetAll(c, &p)
if err != nil {
return nil, err
}
for i := 0; i < len(p); i++ {
p[i].key = k[i]
}
return &p, nil
}
Then it occurred to me to wonder if I could always trust that k
would be in the same order as p
(that is, k[0]
is always the key for p[0]
)? If I understand it correctly the appengine-go source suggests that it would, since both slices are build using append. It certainly seems to work.
Is what I'm doing safe? Is there a better way?
答案1
得分: 3
是的,GetAll返回的键将与附加到dst的值的顺序相同。
英文:
Yes, the keys returned by GetAll will be in the same order as the values appended to dst.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论