go reflect Elem() 深入学习

 示例

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就是实际类型

猜你喜欢

转载自blog.csdn.net/takujo/article/details/105256592