rxmnnxfpvg
rxmnnxfpvg

Reputation: 30993

How to check if interface specifies method using reflection

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!

Upvotes: 7

Views: 622

Answers (1)

James Henstridge
James Henstridge

Reputation: 43899

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))

Upvotes: 9

Related Questions