GetAll:键和实体是否保证按相同顺序返回?

huangapple go评论81阅读模式
英文:

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(&quot;Post&quot;).Order(&quot;-Created&quot;)
	k, err := q.GetAll(c, &amp;p)
	if err != nil {
		return nil, err
	}
	for i := 0; i &lt; len(p); i++ {
		p[i].key = k[i]
	}
	return &amp;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.

huangapple
  • 本文由 发表于 2013年3月3日 10:10:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/15181717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定