首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在golang中遍历一系列的struts

在golang中遍历一系列的struts
EN

Stack Overflow用户
提问于 2022-03-16 07:12:40
回答 2查看 111关注 0票数 0

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

在golang中要做的是迭代具有如下存储值的支柱(这就是我从api中得到的)

代码语言:javascript
运行
复制
[{STOREA 0 0 0} {STOREB 0 0 0} {STOREC 0 0 0} {STORED 0 0 0}]

在python中,我会称这为一个dicts列表。

当我在可视代码中的值上悬停时,它声明如下:

字段itemData []struct{代码字符串“json:”“Code”;项目int“json:”float64“json”;float64“json:”价格“;Qty int”json:“Qty”}

代码语言:javascript
运行
复制
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)
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-03-16 07:20:37

推荐给去切片之旅

然后试试这个:

代码语言:javascript
运行
复制
    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

票数 1
EN

Stack Overflow用户

发布于 2022-03-16 07:25:32

您所做的是一个slice of itemData (struct)。直接使用切片文字来初始化带有值的切片是非常直接的。看起来是这样的:

代码语言:javascript
运行
复制
    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)
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71493012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档