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.

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

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集