Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if interface specifies method using reflection

Tags:

reflection

go

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!

like image 751
atp Avatar asked Nov 16 '13 06:11

atp


1 Answers

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))
like image 92
James Henstridge Avatar answered Oct 12 '22 04:10

James Henstridge