首页 > 解决方案 > `if` 检查 nil 指针结构链中的属性的优雅方法

问题描述

示例(去游乐场

package main

import (
    "fmt"
)

type A struct {
  B *B
}

type B struct {
  C *C
}

type C struct {
  D string
}

func main() {

  a := A{}

  // I'd like to avoid this repetitive statements
  if a.B != nil && a.B.C != nil && a.B.C.D != "" {
    fmt.Println("no nil-pointer panic here")
  }

  // I'd like to go into that if body if any of these are nil and D is not empty string
  if a.B.C.D != "" {
    fmt.Println("nil-pointer panic here")
  }

}

我想不出一种方法来检查指针链中的属性是否为空,这也应该导致false它们中的任何一个是否为空。假设这些字段的名称有点长——并且结构有点复杂——这很快就会变得不可读。但也许没有别的办法...

标签: pointersgo

解决方案


推荐阅读