添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
var r io.Reader = os.Stdin // os.Stdin is of type *os.File which implements io.Reader
v := reflect.ValueOf(r) // r is interface wrapping *os.File value
fmt.Println(v.Type())   // *os.File
v2 := reflect.ValueOf(&r)            // pointer passed, will be wrapped in interface{}
fmt.Println(v2.Type())               // *io.Reader
fmt.Println(v2.Elem().Type())        // navigate to pointed: io.Reader (interface type)
fmt.Println(v2.Elem().Elem().Type()) // 2nd Elem(): get concrete value in interface: *os.File

传入是指针的话,像一种层级递进关系,valueof.type获取的是变量的表面类型,第一次elem.type获取的是此变量的接口类型,再一次就是实际值或类型 ;

非指针传入的话,则.type就是实际类型

示例var r io.Reader = os.Stdin // os.Stdin is of type *os.File which implements io.Readerv := reflect.ValueOf(r) // r is interface wrapping *os.File valuefmt.Println(v.Type()) // *os.Filev2 :... 1.3 基本类型 1.4 引 类型 1.5 类型转换 1.6 字符串 1.7 指针 1.8 定义类型 第 2 章 表达式 2.1 保留字 2.2 运算符 2.3 初始化 2.4 控制流 第 3 章 函数 3.1 函数定义 3.2 变参 3.3 返回值 3.4 匿名函数 3.5 延迟调 3.6 错误处理 第 4 章 数据 4.1 Array 4.2 Slice 4.3 Map 4.4 Struct 第 5 章 法 5.1 法定义 5.2 匿名字段 5.3 法集 5.4 表达式 具有re flec t库的100%兼容性API 使用re flec t.Type功能时不会发生分配 创建re flec t.Value时,可以选择转义( re flec t.ValueOf )或noescape( re flec t.ValueNoEscapeOf ) 反射库中的所有测试均已通过,但使用某些私有函数的测试除外。 go get github.com/goccy/go-re flec t 将import语句从re flec t替换为github.com/goccy/go-re flec t -import " re flec t " +import " github.com/goccy/go-re flec t " 关于re flec t.Type的基准 $ go test -bench TypeOf goos: darwin goarch: a
golang re flec t反射之 Elem ()方法 可以看到 对于 Type类型的funcTyp,直接取Kind时,它的类型为ptr,也就是在反射中所有的指针类型都是ptr,但是当我们想要获取指针背后元素的真正数据类型时就需要使用 Elem 方法, Elem 源码如下(省略了多个case,只关注Pointer): 可以看到它是把指针类型的保存的地址取出来,然后转换为Type类型。
recover from panic situation: - re flec t: call of re flec t.Value. Elem on struct Value golang报错 recover from panic situation: - re flec t: call of re flec t.Value. Elem on struct Value 原因是该传,指针的地方没传。
在 Go 中,可以使用反射来获取类型中所有方法的名称列表。可以使用 re flec t.TypeOf() 函数获取类型的反射类型,然后使用 NumMethod() 和 Method(i) 函数来遍历类型中的所有方法。示例代码如下: package main import ( "fmt" "re flec t" type Example struct{} func (e *Example) Method1() {} func (e *Example) Method2() {} func main() { var e Example t := re flec t.TypeOf(e) for i := 0; i < t.NumMethod(); i++ { fmt.Println(t.Method(i).Name) 其中,Example 是要获取方法列表的类型,Method1 和 Method2 是示例类型的两个方法。