douxianji6104 2018-11-28 09:12
浏览 742

如何在Golang中使用for循环在struct中存储值

I want to store values in a struct. I have multiple set of datas and while iterating those set of data, I have to store those sets into struct. I should also have the previous stored data along with the currently stored.

Please find the code i am using

    package main
    import (
      "fmt"
    )

    type saveDetails struct {
      ID string
      Grade string
      Regular string
      OpeningKey string
    }

    func main() {
       tagsList := []saveDetails {}
       results = [{ {1000000001 A Regular JOBOp123}} { {1000000002 B Regular JOBOp234}} { {1000000003 C  Regular JOBOp456}}]

       for _, details := range results {
          tagsList = append(tagsList, saveDetails {ID: details.ID, Grade:details.Grade, Regular:details.Regular, OpeningKey:details.OpeningKey})
       }
       fmt.Println("saveDetails :",tagsList )
     }

Please help me in resolving this issue. I am new to this array and structs in golang. I am not sure whether i could use the append function. It could be very much helpful if i get an working code.

  • 写回答

2条回答 默认 最新

  • dongqiaozhe5070 2018-11-28 09:17
    关注

    This is a valid and working version of your code:

    package main
    
    import (
        "fmt"
    )
    
    type saveDetails struct {
        ID         string
        Grade      string
        Regular    string
        OpeningKey string
    }
    
    func main() {
        var tagsList []saveDetails
        results := []saveDetails{saveDetails{ID: "1000000001", Grade: "A", Regular: "Regular", OpeningKey: "JOBOp123"}, saveDetails{ID: "1000000001", Grade: "A", Regular: "Regular", OpeningKey: "JOBOp123"}}
    
        for _, details := range results {
            tagsList = append(tagsList, saveDetails{
                ID: details.ID, Grade: details.Grade, Regular: details.Regular, OpeningKey: details.OpeningKey,
            })
        }
        fmt.Println("saveDetails :", tagsList)
    }
    

    https://play.golang.org/p/vVQGPTnph6z

    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用