October 2015
Beginner to intermediate
400 pages
14h 44m
English
Our final example of reflection uses reflect.Type to print the
type of an arbitrary value and enumerate its methods:
// Print prints the method set of the value x.
func Print(x interface{}) {
v := reflect.ValueOf(x)
t := v.Type()
fmt.Printf("type %s\n", t)
for i := 0; i < v.NumMethod(); i++ {
methType := v.Method(i).Type()
fmt.Printf("func (%s) %s%s\n", t, t.Method(i).Name,
strings.TrimPrefix(methType.String(), "func"))
}
}
Both reflect.Type and reflect.Value have a method called
Method.
Each t.Method(i)
call returns an instance of reflect.Method, a struct type
that describes the name and type of a single method.
Each v.Method(i) call returns a reflect.Value ...