我想知道具体类型是否实现了一个specefic接口并将其打印出来.我编写了一个带有自定义结构(MyPoint)的示例[0],而不是接口类型.MyPoint具有io.Reader接口中定义的Read函数:
type MyPoint struct {
X, Y int
}
func (pnt *MyPoint) Read(p []byte) (n int, err error) {
return 42, nil
}
Run Code Online (Sandbox Code Playgroud)
目的是获取具体类型p实现接口io.Writer的信息.因此,我写了一个简短的主要内容来获得支票.
func main() {
p := MyPoint{1, 2}
}
Run Code Online (Sandbox Code Playgroud)
第一个想法是在反射和类型开关的帮助下检查它并添加check(p)到主函数.
func checkType(tst interface{}) {
switch tst.(type) {
case nil:
fmt.Printf("nil")
case *io.Reader:
fmt.Printf("p is of type io.Reader\n")
case MyPoint:
fmt.Printf("p is of type MyPoint\n")
default:
fmt.Println("p is unknown.")
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:p is of type MyPoint.经过一些研究,我知道我应该预料到,因为Go的类型是静态的,因此p的类型是MyPoint而不是io.Reader.除此之外,io.Reader是一种与MyPoint类型不同的接口类型.
我在[1]找到了一个解决方案,它检查MyPoint在编译时是否可以是io.Reader.有用.
var _ io.Reader = (*MyPoint)(nil)
Run Code Online (Sandbox Code Playgroud)
但这不是我想要的解决方案.下面的尝试也失败了.我认为这是因为上面的原因,不是吗?
i …Run Code Online (Sandbox Code Playgroud)