doulang6013 2019-03-31 12:22
浏览 201

如何从Go中的循环返回数据?

I'm trying to convert a []*Struct to a JSON response, I'm able to get the data from the []*Struct and iterate over it. The part I get stuck around is the iterating over a loop then returning the data to an interface{}

I've tried to putting an interface in an interface, but I just can't make ends meet. Here's what I have at the moment, I was told to turn to StackOverflow if I had any issues.

package main

import (
   "log"
   "context"
   "cloud.google.com/go/datastore"
)

var ctx = context.Background()

type ItemList struct {
    Id    string    `datastore:"_id"`
    Name  string    `datastore:"name"`
}

type Data struct {
    ManyItems   []Item
}

type Item struct {
    Id    string    `json:"id"`
    Name  string    `json:"name"`
}

func Get() ([]*ItemList, error) {
  client, err := datastore.NewClient(ctx, "project-name")
  if err != nil {
     log.Println(err)
  }

  var Response []*ItemList
  query := datastore.NewQuery("query")
  _, err = client.GetAll(ctx, query, &Response)
  if err != nil {
     log.Println(err)
  }

  return Response, error
}

func Read() (interface{}) {
   resp, err := Get()
   if err != nil {
      log.Println(err)
   }

   for i, _ := range resp {
     // this is where i get stuck
     r := &Data{
               ManyItems: Item{
                        Id: resp[i].Id,
                        Name: resp[i].Name,
               },
          }
     return r
   }
}

Thank you to anyone who reads this or can provide me some sort of guidance, I really appreciate it.

  • 写回答

2条回答 默认 最新

  • douli4337 2019-03-31 13:19
    关注

    You can predeclare a *Data variable and then inside the loop, on each iteration add the item to its ManyItems field. Since ItemList and Item have the same structure, ie the same fields in the same order, you can convert directly one to the other. (As long as you are on Go 1.8 or newer)

    func Read() interface{} {
        resp, err := Get()
        if err != nil {
            log.Println(err)
            return nil
        }
    
        data := &Data{ManyItems: make([]Item, len(resp))}
        for i := range resp {
            data.ManyItems[i] = Item(*resp[i])
        }
        return data
    }
    

    However if possible it would be more efficient to just return the slice you already have, something like this.

    type ItemList struct {
        Id   string `datastore:"_id" json:"id"`
        Name string `datastore:"name" json:"name"`
    }
    
    type Data struct {
        ManyItems []*ItemList
    }
    
    func Read() interface{} {
        resp, err := Get()
        if err != nil {
            log.Println(err)
            return nil
        }
    
        return &Data{ManyItems: resp}
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?