Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: check whether type of value is function

How I can check that some variable in golang has type func, like this:

func A() {}

func main() {
    variable := A
    isFunc := IsFunc(variable) // true or false
}
like image 429
Alex Saskevich Avatar asked Dec 19 '14 16:12

Alex Saskevich


People also ask

How do I know the type of a value in Go?

A quick way to check the type of a value in Go is by using the %T verb in conjunction with fmt. Printf . This works well if you want to print the type to the console for debugging purposes.

How do you check if a value is a function?

Use the typeof operator to check if a function is defined, e.g. typeof myFunction === 'function' . The typeof operator returns a string that indicates the type of a value. If the function is not defined, the typeof operator returns "undefined" and doesn't throw an error. Copied!

Is function a type in Golang?

As mentioned above, function types are one kind of types in Go. A value of a function type is called a function value. The zero values of function types are represented with the predeclared nil .

What does func () mean in Golang?

func: It is a keyword in Go language, which is used to create a function. function_name: It is the name of the function. Parameter-list: It contains the name and the type of the function parameters. Return_type: It is optional and it contain the types of the values that function returns.


2 Answers

func IsFunc(v interface{}) bool {
   return reflect.TypeOf(v).Kind() == reflect.Func
}
like image 55
Bayta Darell Avatar answered Sep 27 '22 23:09

Bayta Darell


Already solved with this:

func IsFunc(fn interface{}) bool {
    return reflect.TypeOf(fn).Kind() == reflect.Func
}
like image 43
Alex Saskevich Avatar answered Sep 27 '22 23:09

Alex Saskevich