4

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?

buraky
  • 937
  • 1
  • 11
  • 18

1 Answers1

5

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.

buraky
  • 937
  • 1
  • 11
  • 18