Discovered a possible bug in the reflect package related to number comparison.

blov · · 685 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p><code>reflect.DeepEqual()</code> fails unless both values are the exact same type, and for this purpose, hard-coded numbers count as <code>int</code>. Here&#39;s a simple example that demonstrates how it can fail even though it&#39;s comparing 0 with 0:</p> <p><a href="http://play.golang.org/p/_l7cH3qzWj" rel="nofollow">http://play.golang.org/p/_l7cH3qzWj</a></p> <p>Modifying the example to incorporate one of these fixes causes it to behave as expected:</p> <ol> <li>Change the declaration of x to <code>var x int = 0</code> or <code>x := 0</code>.</li> <li>Compare it to <code>int32(0)</code> instead of plain <code>0</code>.</li> <li>Use <code>==</code> instead.</li> </ol> <p>I ended up running into this because testify&#39;s assert package uses <code>reflect.DeepEqual()</code> under the hood for its equality tests, and a call to <code>assert.NotEqual()</code> was not returning the value that I expected it to.</p> <p>Would it be worth filing a bug report? The documentation for DeepEqual says that &#34;It uses normal == equality where possible but will scan elements of arrays, slices, maps, and fields of structs&#34;, but here, == equality returns a different (and more correct) value despite the value being primitive.</p> <hr/>**评论:**<br/><br/>hereatendill: <pre><p>That&#39;s what reflect.DeepEqual() is for. If it returned true when given two values of different types, what&#39;s the point of having it?</p> <p>Maybe you need to be using this instead of assert.Equal? <a href="https://godoc.org/github.com/stretchr/testify/assert#EqualValues" rel="nofollow">https://godoc.org/github.com/stretchr/testify/assert#EqualValues</a> (although I don&#39;t see a corresponding NotEqualValues function - that might be something to raise an issue about).</p></pre>TheMerovius: <pre><p>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&#39;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).</p> <p>So, not a bug :)</p> <p>[0] <a href="http://golang.org/ref/spec#Constants" rel="nofollow">http://golang.org/ref/spec#Constants</a></p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

685 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传