2

I have a struct that has elements which are a struct and so on.

Let's say I'm assigning as below:

validFrom := dkdm.AuthenticatedPublic.RequiredExtensions.KDMRequiredExtensions.ContentKeysNotValidBefore This data is dynamic and any element at anytime, can be nil due to 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 in the element and check the value chain one by one and return only if no element is nil.

validFrom := checkAndAssign(dkdm.AuthenticatedPublic.RequiredExtensions.KDMRequiredExtensions.ContentKeysNotValidBefore)

I tried if statements before the assignment but would like to have a cleaner way.

if dkdm.AuthenticatedPublic.RequiredExtensions != nil &&
    dkdm.AuthenticatedPublic.RequiredExtensions.KDMRequiredExtension != nil {
      validFrom = dkdm.AuthenticatedPublic.RequiredExtensions.KDMRequiredExtensions.ContentKeysNotValidBefore
}
Arun
  • 57
  • 4

1 Answers1

3

Is it possible to have a method that takes in the element and check the value chain one by one and return only if no element is nil.

No, there is no such syntax or tooling in Go.

I tried if statements before the assignment but would like to have a cleaner way.

The if statement is the "clean" way. You can shorten it a bit by introducing a new variable like

if re := dkdm.AuthenticatedPublic.RequiredExtensions; re != nil && 
    re.KDMRequiredExtension != nil  {
    ....
}
Volker
  • 40,468
  • 7
  • 81
  • 87