go DeepEqual
const min = 1.00000001
func cmp() {
var float32Val float32 = 1.0
var float32ValCmp float32 = min
if float32Val == float32ValCmp {
fmt.Println("ret1")
}
if float32Val == min {
fmt.Println("ret2")
}
if reflect.DeepEqual(float32Val, min) {
fmt.Println("ret3")
}
}
在这个测试中,ret1、ret2是能够打印出结果的。但是为什么用DeepEqual不能够打印出正常结果呢?
引用API中的说明,理解的意思不是说DeepEqual和 == 的作用是一样的吗?
Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.
In general DeepEqual is a recursive relaxation of Go's == operator. However, this idea is impossible to implement without some inconsistency. Specifically, it is possible for a value to be unequal to itself, either because it is of func type (uncomparable in general) or because it is a floating-point NaN value (not equal to itself in floating-point comparison), or because it is an array, struct, or interface containing such a value. On the other hand, pointer values are always equal to themselves, even if they point at or contain such problematic values, because they compare equal using Go's == operator, and that is a sufficient condition to be deeply equal, regardless of content. DeepEqual has been defined so that the same short-cut applies to slices and maps: if x and y are the same slice or the same map, they are deeply equal regardless of content.
reference:https://golang.org/pkg/reflect/#DeepEqual
1.00000001 已经超过了float32的精度,为float64类型。
== 和 DeepEqual 不一样的地方在于。DeepEqual认为相等的基础是类型一致。就是两者必须同为float32或者float64。而==在比较的时候会做一个类型转换,将高精度类型转化为低精度类型,所以会将1.00000001转化为低精度的float32来进行比较。
浙公网安备 33010602011771号