reflect.DeepEqual()
fails unless both values are the exact same type, and for this purpose, hard-coded numbers count as int
. Here's a simple example that demonstrates how it can fail even though it's comparing 0 with 0:
http://play.golang.org/p/_l7cH3qzWj
Modifying the example to incorporate one of these fixes causes it to behave as expected:
- Change the declaration of x to
var x int = 0
orx := 0
. - Compare it to
int32(0)
instead of plain0
. - Use
==
instead.
I ended up running into this because testify's assert package uses reflect.DeepEqual()
under the hood for its equality tests, and a call to assert.NotEqual()
was not returning the value that I expected it to.
Would it be worth filing a bug report? The documentation for DeepEqual says that "It uses normal == equality where possible but will scan elements of arrays, slices, maps, and fields of structs", but here, == equality returns a different (and more correct) value despite the value being primitive.
评论:
hereatendill:
TheMerovius:That's what reflect.DeepEqual() is for. If it returned true when given two values of different types, what's the point of having it?
Maybe you need to be using this instead of assert.Equal? https://godoc.org/github.com/stretchr/testify/assert#EqualValues (although I don't see a corresponding NotEqualValues function - that might be something to raise an issue about).
This behaviour is as to spec [0]. An integer-literal is an untyped constant. It gets assigned a type, when used as an expression (i.e. the call to reflect.DeepEqual). As DeepEqual takes an interface{}, the type infered is the default type for integer untyped constants, which is int. As mentioned, DeepEqual returns false, if types don't match, so you have to make the types match (by making x an int, or making the untyped constant to a constant of a different type).
So, not a bug :)
