Home >Backend Development >Golang >Check for nil and then assign value from structure
#php editor Strawberry will introduce to you a common programming technique today - "check nil and then assign value from the structure". When writing code, we often encounter situations where we need to obtain the value of a certain field from a structure. However, due to the possibility of nil values, taking the value directly may cause the program to crash. In order to solve this problem, we need to perform a nil check before taking the value to ensure the stability of the program. This article will introduce the specific implementation of this technique in detail to help readers better understand and apply it in actual development.
I have a structure, which contains elements such as structure.
Let's say my allocation is as follows:
validfrom := dkdm.authenticatedpublic.requiredextensions.kdmrequiredextensions.contentkeysnotvalidbefore
This data is dynamic and any element at any time may be zero due to a parsing error or no data.
For example, kdmrequiredextensions
can be nil and when I try to access contentkeysnotvalidbefore
it will throw a nil pointer reference error.
Is it possible to have a method that takes elements and checks the chain of values one by one, returning only if no element is nil.
validfrom := checkandassign(dkdm.authenticatedpublic.requiredextensions.kdmrequiredextensions.contentkeysnotvalidbefore)
I tried an if statement before the assignment, but was hoping for a cleaner way.
if dkdm.AuthenticatedPublic.RequiredExtensions != nil && dkdm.AuthenticatedPublic.RequiredExtensions.KDMRequiredExtension != nil { validFrom = dkdm.AuthenticatedPublic.RequiredExtensions.KDMRequiredExtensions.ContentKeysNotValidBefore }
Is it possible to have a method that accepts elements and checks the chain of values one by one, returning only if no element is nil.
No, there is no such syntax or tools in go.
I tried an if statement before the assignment, but was hoping for a cleaner way.
if
The statement is the "clean" way. You can shorten it by introducing a new variable like
if re := dkdm.AuthenticatedPublic.RequiredExtensions; re != nil && re.KDMRequiredExtension != nil { .... }
The above is the detailed content of Check for nil and then assign value from structure. For more information, please follow other related articles on the PHP Chinese website!