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
}
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.
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!
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 .
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.
func IsFunc(v interface{}) bool {
return reflect.TypeOf(v).Kind() == reflect.Func
}
Already solved with this:
func IsFunc(fn interface{}) bool {
return reflect.TypeOf(fn).Kind() == reflect.Func
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With