cmp.Equal出现恐慌信息:”无法处理未导出的字段在..”

huangapple go评论94阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年8月25日 00:28:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/73476661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定