I want to write a function which takes a pointer to any type of function. I could do:
func myFunc(f interface{})
...but that would allow non-function values. Is there any way I can restrict the type to any function?
I want to write a function which takes a pointer to any type of function. I could do:
func myFunc(f interface{})
...but that would allow non-function values. Is there any way I can restrict the type to any function?
Assuming you literally mean any function, you can either do a type switch (which would be specific):
switch v.(type) {
case func() int:
case func() string:
}
Or you could use the reflect
package to determine the type:
if reflect.TypeOf(v).Kind() != reflect.Func {
// error here
}
This is a runtime solution. Other than that, there's nothing else you can do. The downside about this is the compiler won't stop someone from passing a non-function value.
Personally I would avoid doing this, and I would expect a specific func prototype, like:
func myFunc(f func() string)
With this you're less likely to have errors when the compiler knows what the types are.