<pre><code>package main
import (
"fmt"
"reflect"
)
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
<nil></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't "stack"; 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("method").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'm not sure if the spec is completely explicit about this (I thought it was, but I can'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's only one representation of a <code>nil</code> interface, with no particular type.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传