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
}
棘手的一点是要注意如何处理指针。
- 2 回答
- 0 关注
- 171 浏览
添加回答
举报