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?