1

Give a function:

type myFunc func(...interface{}) (interface{})

I'd like to get the type of myFunc, something like:

t := reflect.TypeOf(myFunc)

Or

t := reflect.TypeOf((*myFunc)(nil))

The only way I have found to do this is by first creating a temporary variable of myFunc and then getting the TypeOf from that.

var v myFunc
t := reflect.TypeOf(v)

Is there a better way to do this?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ElfsЯUs
  • 1,188
  • 4
  • 14
  • 34
  • See related / possible duplicates: [Golang TypeOf without an instance and passing result to a func](https://stackoverflow.com/questions/48939416/golang-typeof-without-an-instance-and-passing-result-to-a-func/48944430#48944430); and [How to get the string representation of a type?](https://stackoverflow.com/questions/41905222/how-to-get-the-string-representation-of-a-type/41905585#41905585) – icza Mar 01 '18 at 07:18

1 Answers1

3

The simplest way to get the function type would be reflect.TypeOf(myFunc(nil)).

package main

import (
    "fmt"
    "reflect"
)

type myFunc func(...interface{}) interface{}

func main() {
    t := reflect.TypeOf(myFunc(nil))

    // Print whether function type is variadic
    fmt.Println("Variadic =", t.IsVariadic())

    // Print out every input type
    for i := 0; i < t.NumIn(); i++ {
        fmt.Println("In", i, "=", t.In(i))
    }

    // Print out every output type
    for i := 0; i < t.NumOut(); i++ {
        fmt.Println("Out", i, "=", t.Out(i))
    }
}
dtolnay
  • 9,621
  • 5
  • 41
  • 62