How do I find which struct field is different when comparing two structs using reflect.DeepEqual(). When I print the struct values then I don't see any difference between the 2 struct values but still the reflect.DeepEqual() method returns false
1 Answer
As pointed our by kostix in his (now deleted) answer https://github.com/go-test/deep is very useful. It helped me find my issues in minutes when comparing large structures based on XML/JSON documents.
diff := deep.Equal(got, want)
if diff != nil {
t.Errorf("compare failed: %v", diff)
}
With the standard reflect package, I had to more or less implement the diff myself, but in this case it works and the diff shows all the field names up to the values which differ. It makes it really easy to find your issues.
2 Comments
asap diablo
it can only tell u that got is not equal to want, but not got.x != want.x
Alexis Wilke
Yes. It tells me whether
got.x != want.x and if you have 100 fields, it still only tells you that got.x != want.x instead of showing all the fields like the reflect.Equal() does. Way better. You have to write the diff as shown in my example to see the reduced output.
"%#v"will not, for example, print values pointed to by pointers, so you would have no way of detecting if a two pointer fields point to two values that are equal.