#Function that can call any function

9 messages · Page 1 of 1 (latest)

real hare
#

Is there any way to have a function that can take any function and its argument and call it?

gritty egret
#

yes if their signatures match

lilac shadow
#
func dosomething(i int, f func(int)) {
     f(i)
}

func multiply(i int): int {
    return i * 2
}

func main() {
      dosomething(2, multiply)
}
frozen cedar
real hare
#

Yea I meant using reflect to find out the function type and calling the function using the variadic slice of interface

#
func dosomething(f interface{}, args ...interface{}) {
#

something like this

#

I can always work around it by using

func dosomething(f func())

and just pass in a closure that just calls the function but was wondering if there was any other way to do it

gritty egret
#

well if we're talking reflect you can use reflect.Type's NumIn()/NumOut() with In()/Out() to get input args/output values and IsVariadic for variadic checks and then use reflect.Value.Call(Slice) as mentioned above. Sounds doable but I personally only worked with In/Out