Reflection Basics
Method Lookup
Reflection can check whether a type exposes a named method.
Method Lookup
method_lookup.go
package main
import (
"fmt"
"reflect"
)
type Report struct {
Title string
}
func (r Report) Summary() string {
return "report:" + r.Title
}
func main() {
var methodName =
reportType := reflect.TypeOf(Report{})
method, ok := reportType.MethodByName(methodName)
methodType := "none"
if ok {
methodType = method.Type.String()
}
fmt.Println("method_name=", methodName)
fmt.Println("found=", ok)
fmt.Println("method_count=", reportType.NumMethod())
fmt.Println("method_type=", methodType)
}
package main
import (
"fmt"
"reflect"
)
type Report struct {
Title string
}
func (r Report) Summary() string {
return "report:" + r.Title
}
func main() {
var methodName =
reportType := reflect.TypeOf(Report{})
method, ok := reportType.MethodByName(methodName)
methodType := "none"
if ok {
methodType = method.Type.String()
}
fmt.Println("method_name=", methodName)
fmt.Println("found=", ok)
fmt.Println("method_count=", reportType.NumMethod())
fmt.Println("method_type=", methodType)
}
methods
Use method lookup for inspection and adapters, but keep normal code paths explicit when possible.