dsplos5731 2017-05-07 18:36
浏览 3
已采纳

如何使Go追加在范围循环内工作

I have this function which takes an unknown amount of input from a struct:

func GetAllXXXByQueryFilters(ctx context.Context, filters ...XXXFilters) ([]XXX, error) {
    var allKeys []*datastore.Key
    var xxx []XXX
    for _, filter := range filters {
        query := datastore.NewQuery("XXX")
        if filter.Foo != "" {
            query = query.Filter("foo =", filter.Foo)
        }
        if filter.Bar != "" {
            query = query.Filter("bar =", filter.Bar)
        }
        keys, err := models.DSClient().GetAll(ctx, query, &xxx)
        if err != nil {
            return nil, err
        }
        allKeys = append(keys) // PROBLEM HERE
    }
    for i, key := range allKeys {
        xxx[i].ID = key.ID
    }
    return xxx, nil
}

The problem is that allKeys will override previous query results. I have previously overcome the problem by doing:

keys1, err := models.DSClient().GetAll(ctx, query1, &xxx)
keys2, err := models.DSClient().GetAll(ctx, query2, &xxx)
keys = append(keys1, keys2...)

But I wanted my GetAllXXXByQueryFilters to be more sophisticated and avoid duplicated code, and now I can't seem to figure out how I can store the keys from the for _, filter := range filters loop and then append them all afterwards. So I was hoping that maybe there was a smarter way to do/replace the allKeys = append(keys) line so that it doesn't override previous keys?

  • 写回答

1条回答 默认 最新

  • duannian7116 2017-05-07 18:42
    关注

    Append to the slice like this:

    allKeys = append(allKeys, keys...) 
    

    The first argument to append is the slice. The remaining arguments are the elements to append to the slice. The append function returns the new slice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改