遍历 golang 中的一系列 struts

我的术语可能不适用,所以我使用了一些 python 术语。


在 golang 中尝试做的是迭代一个具有这样存储值的支柱(这是我从 api 返回的)


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

在 python 中,我将其称为字典列表。


当我将鼠标悬停在可视代码中的值上时,它指出:


field itemData []struct{代码字符串 "json:"Code""; 项目 int "json:"项目""; 价格 float64 "json:"价格""; 数量 int "json:"数量""}


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)

    }


繁星coding
浏览 82回答 2
2回答

30秒到达战场

推荐给Go 之旅 - Slice然后试试这个:    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

函数式编程

你所拥有的slice是itemData( struct)。使用切片文字用值初始化切片非常简单。它看起来像这样:    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)    }
打开App,查看更多内容
随时随地看视频慕课网APP