Skip to content

Commit

Permalink
Fix exporter to handle nil interface values (#207)
Browse files Browse the repository at this point in the history
A shallow copy with reflect.ValueOf(v.Interface()) does not work
if v is a nil interface value. Special case the edge case by
checking for a nil value and create a new one use reflect.Zero.
  • Loading branch information
dsnet authored Jun 9, 2020
1 parent 11c4583 commit 23a2b56
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
2 changes: 1 addition & 1 deletion cmp/compare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,7 @@ func comparerTests() []test {
}, {
label: label,
x: struct{ s fmt.Stringer }{new(bytes.Buffer)},
y: struct{ s fmt.Stringer }{new(bytes.Buffer)},
y: struct{ s fmt.Stringer }{nil},
opts: []cmp.Option{
cmp.AllowUnexported(struct{ s fmt.Stringer }{}),
cmp.FilterPath(func(p cmp.Path) bool {
Expand Down
5 changes: 4 additions & 1 deletion cmp/export_unsafe.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool)
// If the original parent value was not addressable, shallow copy the
// value to make it non-addressable to avoid leaking an implementation
// detail of how forcibly exporting a field works.
ve = reflect.ValueOf(ve.Interface()).Convert(f.Type)
if ve.Kind() == reflect.Interface && ve.IsNil() {
return reflect.Zero(f.Type)
}
return reflect.ValueOf(ve.Interface()).Convert(f.Type)
}
return ve
}

0 comments on commit 23a2b56

Please sign in to comment.