登录
首页 >  Golang >  Go问答

在 golang 中迭代遍历结构体数组

来源:stackoverflow

时间:2024-03-14 19:21:24 160浏览 收藏

大家好,我们又见面了啊~本文《在 golang 中迭代遍历结构体数组》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

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

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

[{storea 0 0 0} {storeb 0 0 0} {storec 0 0 0} {stored 0 0 0}]

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

当我将鼠标悬停在可视代码中的值上时,它会显示以下内容:

field itemdata []struct{code string "json:"code"";项目整数 "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)
    }

正确答案


建议给A Tour of 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

您拥有的是 itemdata (struct) 的 slice。使用切片文字来用值初始化切片非常简单。它看起来像这样:

    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)
    }

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>