7

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 reflection 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!

1 Answer 1

9

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's pretty crafty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.