英文:
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
,我只想访问Sku
和Status
的值,是否可以像这样做:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论