pointers - `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
它们中的任何一个是否为空。假设这些字段的名称有点长——并且结构有点复杂——这很快就会变得不可读。但也许没有别的办法...
解决方案
推荐阅读
- laravel - Laravel - 在返回之前不要显示消息
- javascript - 下一个/上一个按钮上的图像描述
- css - 如何使工具提示在使用 css 溢出隐藏的容器中可见?
- indexing - Julia - 使用带有数组的 CartesianIndices
- pandas - 当键不在索引中时,如何(惯用地)使用 pandas .loc 返回一个空数据框
- python - 安装 OpenCV 失败,因为它找不到“skbuild”
- mongodb - 如何在 nginx 容器中启用流模块
- jsf - 如何使 ajax 在 t:datatable 列中工作,其中 t:datatable 位于 t:datalist 中?
- python - 打开具有绝对路径的文件时出现 FileNotFoundError
- python - 错误,“[错误] 33#33: *92500 connect() failed (111: Connection denied) while connection to upstream, client: 216.58.212.244, server: #1906