检查 nil 后,从结构体中分配值

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

Assign values from struct after checking nil

问题

我有一个结构体,其中的元素也是一个结构体,以此类推。

假设我进行如下赋值:

validFrom := dkdm.AuthenticatedPublic.RequiredExtensions.KDMRequiredExtensions.ContentKeysNotValidBefore

这个数据是动态的,任何元素在任何时候都可能为nil,这可能是由于解析错误或没有数据。

例如,KDMRequiredExtensions 可能为nil,当我尝试访问 ContentKeysNotValidBefore 时,会抛出一个空指针引用错误。

是否可能有一个方法,接受这个元素并逐个检查值链,只有当没有元素为nil时才返回。

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

我尝试在赋值之前使用if语句,但希望有一种更简洁的方式。

if dkdm.AuthenticatedPublic.RequiredExtensions != nil &&
    dkdm.AuthenticatedPublic.RequiredExtensions.KDMRequiredExtension != nil {
      validFrom = dkdm.AuthenticatedPublic.RequiredExtensions.KDMRequiredExtensions.ContentKeysNotValidBefore
}
英文:

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
}

答案1

得分: 2

可以有一个方法,它接受一个元素并逐个检查值链,只有当没有元素为nil时才返回。在Go语言中,没有这样的语法或工具。

你可以在赋值之前使用if语句,这是一种比较简洁的方式。你可以通过引入一个新的变量来简化它,例如:

if re := dkdm.AuthenticatedPublic.RequiredExtensions; re != nil && 
    re.KDMRequiredExtension != nil  {
    ....
}
英文:

> 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  {
    ....
}

huangapple
  • 本文由 发表于 2023年7月4日 08:40:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76608790.html
匿名

发表评论

匿名网友

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

确定