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

huangapple go评论137阅读模式
英文:

How to access the fields of this struct in 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)

英文:

I'm new to Golang and I need to know how to access the value from a struct of the format:

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"`
}

For example, if I have a variable currentSkus of type CurrentSkuList and I need to access only Sku and Status values, is there a way to do something like:

currentSkus.SubscriptionProducts.Sku?

EDIT! When I try to access currentSkus.Quantity I get a compiler error undefined (type []util.CurrentSkuList has no field or method Quantity).

答案1

得分: 1

是的,有一种方法。你可以通过你提出的.语法来访问。在这种情况下,CurrentSkuList返回的是一个SubscriptionProduct的切片,你可以通过[] struct这部分知道。然后你可以通过以下方式访问数据:

currentSkus.SubscriptionProducts[index].Sku
英文:

Yeah, there is a way. You can access by the . syntax you proposed. In this case, CurrentSkuList is returning an slice of SubscriptionProduct, you know that because of the [] struct part. Then you would have to access to the data this way:

currentSkus.SubscriptionProducts[index].Sku

huangapple
  • 本文由 发表于 2022年4月11日 22:04:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/71829235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定