【发布时间】:2019-05-07 10:58:30
【问题描述】:
我需要知道类型名称及其使用反射的路径。 Type 类型有一个 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)
}
打印
false true *context.valueCtx context.Context
【问题讨论】:
-
对于我的回答者,可运行的游乐场链接:play.golang.org/p/fnjfVl1anv
标签: reflection go