Let*_*tbe 5 comparison struct go go-cmp
我有一个自定义结构,其中有一个未导出的字段。我希望能够将值与此结构的类型进行比较,但我收到如下恐慌消息:
panic: cannot handle unexported field at ...
consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported
Run Code Online (Sandbox Code Playgroud)
示例代码:
panic: cannot handle unexported field at ...
consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported
Run Code Online (Sandbox Code Playgroud)
如何修复此错误并比较变量?
正如错误消息所示,我们可以使用cmp.AllowUnexported函数。这里重要的一点是作为参数,我们应该使用CONTAINS unexported field的类型,而不是未导出字段的类型。
所以最后一行应该这样改变:
result := cmp.Equal(t1, t2, cmp.AllowUnexported(Mytype{}))
Run Code Online (Sandbox Code Playgroud)
另请注意,这cmp.AllowUnexported不适用于子类型递归。如果您的子类型包含未导出的字段,则必须显式传递它们。
| 归档时间: |
|
| 查看次数: |
4008 次 |
| 最近记录: |