10

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

3
  • 2
    Please provide an example. Commented Nov 16, 2017 at 10:48
  • 2
    How are you printing the two struct values? Using "%#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. Commented Nov 16, 2017 at 10:56
  • There was an answer to this question but I dont see it now. There was a useful library link in that answer. Now I couldnt find it Commented Mar 1, 2022 at 9:19

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

it can only tell u that got is not equal to want, but not got.x != want.x
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.