登录
首页 >  Golang >  Go问答

如何在 Golang 中访问该结构体的字段

来源:stackoverflow

时间:2024-02-12 15:30:24 320浏览 收藏

一分耕耘,一分收获!既然都打开这篇《如何在 Golang 中访问该结构体的字段》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我是 golang 新手,我需要知道如何从以下格式的结构中访问值:

type CurrentSkuList struct {
    SubscriptionNumber   string `json:"subscriptionNumber`
    Quantity             int    `json:"quantity"`
    SubscriptionProducts []struct {
        ID              int    `json:"id"`
        ActiveStartDate int    `json:"activeStartDate"`
        ActiveEndDate   int    `json:"activeEndDate"`
        Status          string `json:"status"`
        Sku             string `json:"sku"`
        ChildIDs        []int  `json:"childrenIds"`
    } `json:"subscriptionProducts"`
}

例如,如果我有一个 currentskulist 类型的变量 currentskus 并且我只需要访问 skustatus 值,有没有办法执行类似的操作:

currentskus.subscriptionproducts.sku

编辑!当我尝试访问 currentskus.quantity 时,出现编译器错误 undefined (type []util.currentskulist has no field or method quantity)


正确答案


是的,有办法。您可以通过您建议的 . 语法进行访问。在本例中,currentskulist 返回 subscriptionproduct 的一个切片,您知道这是因为 [] struct 部分。然后您必须通过以下方式访问数据:

currentSkus.SubscriptionProducts[index].Sku

今天关于《如何在 Golang 中访问该结构体的字段》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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