reflect.DeepEqual()
can do it because it has access to unexported features of the reflect
package, in this case namely for the valueInterface()
function, which takes a safe
argument, which denies access to unexported field values via the Value.Interface()
method if safe=true
. reflect.DeepEqual()
will (might) call that passing safe=false
.
You can still do it, but you cannot use Value.Interface()
for unexported fields. Instead you have to use type-specific methods, such as Value.String()
for string
, Value.Float()
for floats, Value.Int()
for ints etc. These will return you a copy of the value (which is enough to inspect it), but will not allow you to modify the field's value (which might be "partly" possible if Value.Interface()
would work and the field type would be a pointer type).
If a field happens to be an interface type, you may use Value.Elem()
to get to the value contained / wrapped by the interface value.
To demonstrate:
type Foo struct {
s string
i int
j interface{}
}
func main() {
x := Foo{"hello", 2, 3.0}
v := reflect.ValueOf(x)
s := v.FieldByName("s")
fmt.Printf("%T %v\n", s.String(), s.String())
i := v.FieldByName("i")
fmt.Printf("%T %v\n", i.Int(), i.Int())
j := v.FieldByName("j").Elem()
fmt.Printf("%T %v\n", j.Float(), j.Float())
}
Output (try it on the Go Playground):
string hello
int64 2
float64 3