<p>Solved: thanks <a href="/u/dilap" rel="nofollow">/u/dilap</a>
I was comparing the reflect.Value's, not the actual interfaces in reflect.DeepEqual().</p>
<p><a href="https://play.golang.org/p/RfHAgoMmDm" rel="nofollow">Go Playground</a></p>
<p><a href="https://pastebin.com/raw/erbE9w4U" rel="nofollow">Pastebin Mirror</a></p>
<p>I just see no reason it won't work:</p>
<ol>
<li><p>It checks to make sure that the interface{} is a slice or array.</p></li>
<li><p>It ranges over the slice/array and if any element of the slice and the supplied value are deeply equal it returns true.</p></li>
<li><p>Otherwise, return false. (Array/Slice does not contain value).</p></li>
</ol>
<p>This reflection stuff is hard :/</p>
<hr/>**评论:**<br/><br/>dilap: <pre><p>Here you go:</p>
<p><a href="https://play.golang.org/p/kgAywwVMym" rel="nofollow">https://play.golang.org/p/kgAywwVMym</a></p>
<p>The problem is that DeepEqual wants the interface{}, not a reflect.Value. The reflect.Value themselves are not equal, but the values they represent are equal.</p>
<p>(As an aside, I would advocate not using reflection for something this. It will be slow, and defeats the type safety the language gives you. I would just write separate versions of contains for each type that you need. E.g., in this case, right conatins for []int. If you also need it for strings, then write containsInt and containsString. Sure, it's some copy-paste code duplication, but so what -- it's simple, fast, easy to understand code.)</p></pre>bkeroack: <pre><p>"[Reflection] is not for you" -- Rob Pike
<a href="https://www.youtube.com/watch?v=PAAkCSZUG1c&t=15m29s" rel="nofollow">https://www.youtube.com/watch?v=PAAkCSZUG1c&t=15m29s</a></p></pre>Franke123: <pre><p>Ah, that makes sense! It was comparing the reflect.Value's, not the underlying interfaces. Thank you for the explanation!</p>
<p>As the response to the aside: I was just doing this for fun to learn about reflection, I usually just do a containsInt type thing for something like this. Thank you so much!</p></pre>dilap: <pre><p>Happy to help!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传