Today discovery about golang. You can't have typed nil of interface

blov · · 313 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<pre><code>package main import ( &#34;fmt&#34; &#34;reflect&#34; ) type X interface {} type Y struct {} func main() { var y Y fmt.Println(reflect.TypeOf(y)) var x X fmt.Println(reflect.TypeOf(x)) } </code></pre> <p>Result: main.Y &lt;nil&gt;</p> <p><a href="https://play.golang.org/p/aT0sBYRtqa">https://play.golang.org/p/aT0sBYRtqa</a></p> <hr/>**评论:**<br/><br/>tv64738: <pre><p>Interfaces don&#39;t &#34;stack&#34;; they have the interface type, and the underlying type. When you pass <code>reflect.TypeOf</code> a value to examine, the value gets assigned to an argument of type <code>interface{}</code>. In this case, the underlying type of that interface value is <code>Y</code>.</p></pre>DeedleFake: <pre><p>You can, however, get an interface <code>reflect.Type</code>. The easiest way to do it is to pass it a pointer to an interface and then get the element type of the pointer type.</p></pre>bartoszgolek: <pre><p>Sure, but I learned that trying to create mock with testify: type X interface {}</p> <pre><code>func (m *mock) method() X { args := m.Called() return args.Get(0).(X) } var t X mock.On(&#34;method&#34;).Return(t); </code></pre> <p>And I was surprise a little bit. I manage this, but still something not obvious.</p></pre>hobbified: <pre><p>Yeah, I&#39;m not sure if the spec is completely explicit about this (I thought it was, but I can&#39;t find it now), but the section on comparison does say that two interfaces compare equal if both contain the value <code>nil</code>, so the <em>sensible</em> extension of this is that there&#39;s only one representation of a <code>nil</code> interface, with no particular type.</p></pre>

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

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