I want to reflect to determine whether or not a Go interface contains certain method signatures. I've dynamically got the names and signatures, previously through reflect
ion on a struct. Here's a simplified example:
package main
import "reflect"
func main() {
type Mover interface {
TurnLeft() bool
// TurnRight is missing.
}
// How would I check whether TurnRight() bool is specified in Mover?
reflect.TypeOf(Mover).MethodByName("TurnRight") // would suffice, but
// fails because you can't instantiate an interface
}
http://play.golang.org/p/Uaidml8KMV. Thanks for your help!
You can create a reflect.Type
for a type with this trick:
tp := reflect.TypeOf((*Mover)(nil)).Elem()
That is, create a typed nil pointer and then get the type of what it points at.
A simple way to determine if a reflect.Type
implements a particular method signature is to use its Implements
method with an appropriate interface type. Something like this should do:
type TurnRighter interface {
TurnRight() bool
}
TurnRighterType := reflect.TypeOf((*TurnRighter)(nil)).Elem()
fmt.Println(tp.Implements(TurnRighterType))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With