简体   繁体   中英

How to iterate a slice within struct in Golang or is it possible to use for loop within struct?

I have two structs. One is for Lottery and one is for Reward. I am using Mysql database. I want to read data from database and write in JSON format. I can able to do that, but i want to have a nested struct where I want to iterate Reward struct within Lottery struct. Can I do that?

Here is my Lottery and Reward struct

type Lottery struct{
    Id int `json:"lottery_id"`
    Lottery string `json:"lottery_name"`
    Description string `json:"lottery_description"`
    Reward []Rew `json:"rewards"`
}

type Rew struct{
    Id int `json:"reward_id"`
    RewardName string `json:"reward_name"`
    Description string `json:"reward_description"`
    Asset int `json:"reward_asset"`
    AssetName string `json:"reward_asset_name"`
}

Here is my code

app.Get("/lottery/{id:int}", func (ctx iris.Context){
        id1 := ctx.Params().GetIntDefault("id",0)

        stmtOut, err := db.Prepare("select lottery_name, lottery_description from lottery_table where id = ?")
        if err !=nil{
            panic(err.Error())
        }
        defer stmtOut.Close()

        var lottery_name, lottery_description string

        err1 := stmtOut.QueryRow(id1).Scan(&lottery_name,&lottery_description)
        if err != nil{
            panic(err1.Error())
        }

        stmtOut1, err := db.Query("select id, reward_name, reward_description, reward_asset, reward_asset_name from rewards_table where lottery_id = ?",id1)
        if err != nil{
            panic(err.Error())
        }
        defer stmtOut1.Close()

        for stmtOut1.Next() {

            var id, reward_asset int
            var reward_name, reward_description, reward_asset_name string

            err2 := stmtOut1.Scan(&id, &reward_name, &reward_description, &reward_asset, &reward_asset_name)
            if err2 != nil {
                panic(err.Error())
            }

                rew := Lottery{
                Id:          id1,
                Lottery:     lottery_name,
                Description: lottery_description,
                Reward : []Rew{Rew{
                    Id:          id,
                    RewardName:  reward_name,
                    Description: reward_description,
                    Asset:       reward_asset,
                    AssetName:   reward_asset_name,
                },
                },
            }

            ctx.JSON(&rew)
        }


    })

When I use the above function, i am getting JSON format like this

{
    "lottery_id": 7,
    "lottery_name": "lottery2",
    "lottery_description": "lottery for 7",
    "rewards": [
        {
            "reward_id": 9,
            "reward_name": "Reward3",
            "reward_description": "Reward for lottery 7",
            "reward_asset": 20,
            "reward_asset_name": "AC"
        }
    ]
}{
    "lottery_id": 7,
    "lottery_name": "lottery2",
    "lottery_description": "lottery for 7",
    "rewards": [
        {
            "reward_id": 10,
            "reward_name": "Reward5",
            "reward_description": "Reward for lottery 7",
            "reward_asset": 15,
            "reward_asset_name": "AC"
        }
    ]
}

But I want to get JSON as

{
"lottery_id":7,
"lottery_name":"lottery2"
"lottery_description":"lottery for 7"
"rewards":[
    {
        "reward_id":9,
        "reward_name": "Reward3",
        "reward_description": "Reward for lottery 7",
        "reward_asset": 20,
        "reward_asset_name": "ABC"
    },
    {   "reward_id":10,
        "reward_name": "Reward5",
        "reward_description": "Reward for lottery 7",
        "reward_asset": 15,
        "reward_asset_name": "ABC"
    },
    {   "reward_id":11,
        "reward_name": "Reward7",
        "reward_description": "Reward for lottery 7",
        "reward_asset": 10,
        "reward_asset_name": "ABC"
    }
    ]
}

How can I iterate within struct? Is it possible to have for loop within the struct? or is there any other method where I can get JSON as above?

Please help me.

Something like this:

app.Get("/lottery/{id:int}", func(ctx iris.Context) {
    id1 := ctx.Params().GetIntDefault("id", 0)

    stmtOut, err := db.Prepare("select lottery_name, lottery_description from lottery_table where id = ?")
    if err != nil {
        panic(err.Error())
    }
    defer stmtOut.Close()

    lot := Lottery{Id: id1}
    err1 := stmtOut.QueryRow(id1).Scan(&lot.Lottery, &lot.Description)
    if err != nil {
        panic(err1.Error())
    }

    stmtOut1, err := db.Query("select id, reward_name, reward_description, reward_asset, reward_asset_name from rewards_table where lottery_id = ?", id1)
    if err != nil {
        panic(err.Error())
    }
    defer stmtOut1.Close()

    for stmtOut1.Next() {
        rew := Rew{}
        err2 := stmtOut1.Scan(&rew.Id, &rew.RewardName, &rew.Description, &rew.Asset, &rew.AssetName)
        if err2 != nil {
            panic(err.Error())
        }
        lot.Reward = append(lot.Reward, rew)

    }
    ctx.JSON(lot)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM