Home > database >  loop over a array of struts in golang
loop over a array of struts in golang

Time:03-17

My terminology maybe off so I'm using some python terms.

What trying to do in golang is iterate over a strut that is has a stored value like this (which is what I get back from the api)

[{STOREA 0 0 0} {STOREB 0 0 0} {STOREC 0 0 0} {STORED 0 0 0}]

In python I would call this a list of dicts.

When I hover over the value in visual code it states this:

field itemData []struct{Code string "json:"Code""; Items int "json:"Items""; Price float64 "json:"Price""; Qty int "json:"Qty""}

package main

// I think this is the right way to interpret what visual code stated
type itemData struct {
    Code string  `json:"Code"`
    Items int     `json:"Items"`
    Price   float64 `json:"Price"`
    Qty int     `json:"Qty"`
    }

//I'm trying to simulate the api response by storing it in a varible like this but I think the [] are an issue and im doing it incorrectly
var storeData = itemData[{STOREA 0 0 0} {STOREB0 0 0} {STOREC 0 0 0} {STORED0 0 0}] // I think the [ ] brackets are causing an issue

//The idea is I can iterate over it like this:
for k,v := range storeData {
    fmt.Printf(k,v)
    }

CodePudding user response:

Recommended to give A Tour of Go - Slice

Then Try this:

    var storeData = []itemData{{"STOREA", 0, 0, 0}, {"STOREB", 0, 0, 0}, {"STOREC", 0, 0, 0}, {"STORED", 0, 0, 0}}
    for k, v := range storeData {
        fmt.Println(k, v)
    }

https://go.dev/play/p/aRaJlqKe00L

CodePudding user response:

What you've is a slice of itemData (struct). It's not that hard to use a slice literal to initialize the slice with values. It looks like this:

    storeData := []itemData{
        {
            Code:  "STOREA",
            Items: 0,
            Price: 0,
            Qty:   0,
        },
        {
            Code:  "STOREB0",
            Items: 0,
            Price: 0,
        },
        {
            Code:  "STOREC",
            Items: 0,
            Price: 0,
            Qty:   0,
        },
        {
            Code:  "STORED0",
            Items: 0,
            Price: 0,
        },
    }
    for i, v := range storeData {
        fmt.Printf("index: %d, value: %v\n", i, v)
    }
  •  Tags:  
  • go
  • Related