为了账号安全,请及时绑定邮箱和手机立即绑定

遍历 golang 中的一系列 struts

遍历 golang 中的一系列 struts

Go
繁星coding 2022-11-23 15:28:29
我的术语可能不适用,所以我使用了一些 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 statedtype 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 incorrectlyvar 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)    }
查看完整描述

2 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

推荐给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


查看完整回答
反对 回复 2022-11-23
?
函数式编程

TA贡献1807条经验 获得超9个赞

你所拥有的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)

    }


查看完整回答
反对 回复 2022-11-23
  • 2 回答
  • 0 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信