Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access the fields of this struct in Golang

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading