英文:
cmp.Equal gives panic message "cannot handle unexported field at .."
问题
我有一个自定义的结构体,其中有一个未导出的字段。我想要能够比较这个结构体类型的值,但是我收到了如下的恐慌信息:
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
示例代码:
type MyType struct {
ExpField int
unexpField string
}
t1 := MyType{ExpField: 1}
t2 := MyType{ExpField: 2}
result := cmp.Equal(t1, t2)
如何修复这个错误并比较变量?
英文:
I have a custom struct which has an unexported field. I want to be able to compare values with type of this struct, but I am receiving panic message like this:
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
Sample Code:
type MyType struct {
ExpField int
unexpField string
}
t1 := MyType{ExpField: 1}
t2 := MyType{ExpField: 2}
result := cmp.Equal(t1, t2)
How to fix this error and compare variables?
答案1
得分: 5
错误消息建议我们使用cmp.AllowUnexported
函数。这里的重要一点是,作为参数,我们应该使用包含未导出字段的类型,而不是未导出字段的类型。
所以最后一行应该改成这样:
result := cmp.Equal(t1, t2, cmp.AllowUnexported(Mytype{}))
另外请注意,cmp.AllowUnexported
对于子类型不会递归地工作。如果你有包含未导出字段的子类型,你必须显式地传递它们。
英文:
As error message suggests, We can use cmp.AllowUnexported
function. The important point here is as parameter we should use the type which CONTAINS unexported field, not the type of the unexported field.
So last line should be changed like this:
result := cmp.Equal(t1, t2, cmp.AllowUnexported(Mytype{}))
Also note that cmp.AllowUnexported
doesn't work recursively for subtypes. If you have subtypes which contains unexported fields, you have to explicitly pass them.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论