我需要使用反射知道类型名称及其路径。typeType
有一个 Name() 和 PkgPath() 方法,但如果该类型是一个接口,则它们都返回空。
但是,如果我反映一个函数并提取其参数的类型信息,我会得到正确的类型信息。我应该假设这是前一种情况的错误吗?无论上下文如何(例如类型函数参数或值的类型),TypeOf 不应该返回相同的类型信息吗?
我知道类型断言,但我并不总是有一个值来执行断言,因此我需要使用 Reflect.Type 信息。
package main
import (
"fmt"
"reflect"
"golang.org/x/net/context"
)
func main() {
c := reflect.TypeOf(withValue(""))
fn := func(context.Context){}
fc := reflect.TypeOf(fn).In(0)
fmt.Println(isContext(c), isContext(fc), c, fc)
}
func isContext(r reflect.Type) bool {
return r.PkgPath() == "golang.org/x/net/context" && r.Name() == "Context"
}
func withValue(v interface{}) context.Context {
return context.WithValue(context.TODO(), "mykey", v)
}
Run Code Online (Sandbox Code Playgroud)
印刷
false true *context.valueCtx context.Context
Run Code Online (Sandbox Code Playgroud)
这是一些工作代码:https://play.golang.org/p/ET8FlguA_C
package main
import (
"fmt"
"reflect"
)
type MyInterface interface {
MyMethod()
}
type MyStruct struct{}
func (ms *MyStruct) MyMethod() {}
func main() {
var structVar MyInterface = &MyStruct{}
c := reflect.TypeOf(structVar)
fn := func(MyInterface) {}
fc := reflect.TypeOf(fn).In(0)
fmt.Println(isMyInterface(c), isMyInterface(fc), c, fc)
// OP expects : "true true main.MyInterface main.MyInterface"
}
func isMyInterface(r reflect.Type) bool {
// TypeOf trick found at https://groups.google.com/forum/#!topic/golang-nuts/qgJy_H2GysY
return r.Implements(reflect.TypeOf((*MyInterface)(nil)).Elem())
}
Run Code Online (Sandbox Code Playgroud)
这是我在找到实际解决方案之前的回答reflect
。我会把它放在这里,因为我认为它仍然有一些有趣的部分。
首先要做的事情是: for c
、 r.PkgPath() 和 r.Name() 为空,因为底层类型是指针 ( *context.valueCtx
)。
要解决这个问题,您可以使用c := reflect.Indirect(reflect.ValueOf(withValue(""))).Type()
但这并不成立isContext(c)
,因为这样你就有了r.PkgPath() == "golang.org/x/net/context" && r.Name() == "valueCtx"
。
检查 var 是否实现接口的最佳方法是放弃反射并使用类型断言,如下所示:
https://play.golang.org/p/td1YaHHej9
package main
import "fmt"
type MyInterface interface {
MyMethod()
}
type MyStruct struct{}
func (ms *MyStruct) MyMethod() {}
func main() {
var structVar MyInterface = &MyStruct{}
fmt.Println(isMyInterface(structVar))
}
func isMyInterface(object interface{}) bool {
_, ok := object.(MyInterface)
return ok
}
Run Code Online (Sandbox Code Playgroud)
您的代码可以按照您预期的方式使用函数参数,因为没有基础值,因此reflect
使用接口类型。但对于任何具体变量,它将使用值的实际类型。
归档时间: |
|
查看次数: |
7610 次 |
最近记录: |