Commit eced964c authored by Matthew Dempsky's avatar Matthew Dempsky Committed by Rob Pike

reflect: document reflect.TypeOf((*Foo)(nil)).Elem() idiom

See also golang-dev discussion:
https://groups.google.com/d/msg/golang-dev/Nk9gnTINlTg/SV8rBt-2__kJ

Change-Id: I49edd98d73400c1757b6085dec86752de569c01a
Reviewed-on: https://go-review.googlesource.com/8923Reviewed-by: 's avatarRob Pike <r@golang.org>
parent eba38fd7
...@@ -6,6 +6,8 @@ package reflect_test ...@@ -6,6 +6,8 @@ package reflect_test
import ( import (
"fmt" "fmt"
"io"
"os"
"reflect" "reflect"
) )
...@@ -64,3 +66,16 @@ func ExampleStructTag() { ...@@ -64,3 +66,16 @@ func ExampleStructTag() {
// Output: // Output:
// blue gopher // blue gopher
} }
func ExampleTypeOf() {
// As interface types are only used for static typing, a
// common idiom to find the reflection Type for an interface
// type Foo is to use a *Foo value.
writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
fileType := reflect.TypeOf((*os.File)(nil))
fmt.Println(fileType.Implements(writerType))
// Output:
// true
}
...@@ -1009,8 +1009,8 @@ func (t *structType) FieldByName(name string) (f StructField, present bool) { ...@@ -1009,8 +1009,8 @@ func (t *structType) FieldByName(name string) (f StructField, present bool) {
return t.FieldByNameFunc(func(s string) bool { return s == name }) return t.FieldByNameFunc(func(s string) bool { return s == name })
} }
// TypeOf returns the reflection Type of the value in the interface{}. // TypeOf returns the reflection Type that represents the dynamic type of i.
// TypeOf(nil) returns nil. // If i is a nil interface value, TypeOf returns nil.
func TypeOf(i interface{}) Type { func TypeOf(i interface{}) Type {
eface := *(*emptyInterface)(unsafe.Pointer(&i)) eface := *(*emptyInterface)(unsafe.Pointer(&i))
return toType(eface.typ) return toType(eface.typ)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment