为了账号安全,请及时绑定邮箱和手机立即绑定

检查变量实现接口,无需编译

检查变量实现接口,无需编译

Go
MMMHUHU 2021-11-01 16:08:37
我想知道具体类型是否实现了特定接口并将其打印出来。我编写了一个示例 [0],其中包含一个不是接口类型的自定义结构 (MyPoint)。MyPoint 具有在 io.Reader 接口中定义的函数 Read:type MyPoint struct {   X, Y int}func (pnt *MyPoint) Read(p []byte) (n int, err error) {    return 42, nil}目的是获取具体类型p实现io.Writer接口的信息。因此,我写了一个简短的主要 trieng 来获得真实的支票。func main() {     p := MyPoint{1, 2}}第一个想法是在反射和类型切换的帮助下检查它并添加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.")    }}输出是:p is of type MyPoint。经过一番研究,我知道我应该预料到这一点,因为 Go 的类型是静态的,因此 p 的类型是 MyPoint 而不是 io.Reader。除此之外,io.Reader 是一种与 MyPoint 类型不同的接口类型。我找到了一个解决方案,例如在 [1] 中,它检查 MyPoint 是否可以在编译时成为 io.Reader。有用。var _ io.Reader = (*MyPoint)(nil)但这不是我想要的解决方案。像下面这样的尝试也失败了。我想是因为上面的原因,不是吗?i := interface{}(new(MyPoint))    if _, ok := i.(io.Reader); ok {        fmt.Println("i is an io.Reader")}pType := reflect.TypeOf(p)if _, ok := pType.(io.Reader); ok {    fmt.Println("The type of p is compatible to io.Reader")}readerType := reflect.TypeOf((*io.Reader)(nil)).Elem()fmt.Printf("p impl. Reader %t \n", pType.Implements(readerType))存在一种不用编译就可以检查p是否实现了接口的解决方案?我希望有人可以帮助我。
查看完整描述

2 回答

?
茅侃侃

TA贡献1842条经验 获得超21个赞

完全有可能用反射包做你想做的事。下面是一个例子:


package main


import (

    "fmt"

    "io"

    "reflect"

)


type Other int


type MyPoint struct {

    X, Y int

}


func (pnt *MyPoint) Read(p []byte) (n int, err error) {

    return 42, nil

}


func check(x interface{}) bool {

    // Declare a type object representing io.Reader

    reader := reflect.TypeOf((*io.Reader)(nil)).Elem()

    // Get a type object of the pointer on the object represented by the parameter

    // and see if it implements io.Reader

    return reflect.PtrTo(reflect.TypeOf(x)).Implements(reader)

}


func main() {


    x := MyPoint{0, 0}

    y := Other(1)


    fmt.Println(check(x)) // true

    fmt.Println(check(y)) // false

}

棘手的一点是要注意如何处理指针。


查看完整回答
反对 回复 2021-11-01
  • 2 回答
  • 0 关注
  • 171 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信