我正在从API检索数据 . struct输出是:
{
StreamSpecification: {
StreamEnabled: true,
StreamViewType: "NEW_AND_OLD_IMAGES"
},
TableStatus: "ACTIVE"
}
但是如果API输出中没有StreamSpecification,我在尝试打印结构时收到以下错误 .
panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=xxxxxxxx]
如何检查值StreamSpecification是否存在于值中?或者如何以任何其他方式解决问题?
2 回答
如果我正确理解了这个问题,我会将结构转换为 Map ,然后检查您感兴趣的字段是否在 Map 中 .
例如:
Go Playground
听起来好像您在第一次确认JSON对象中是否提供了
StreamSpecification
时,是否正在尝试访问StreamEnabled
或StreamViewType
.假设您有内部
StreamSpecification
作为结构的引用,您需要确保StreamSpecification
不是nil
: