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 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信