mercredi 2 mars 2016

Invoke a function which is received as an interface variable in golang

I have a code which is similar to the following

package main

import "fmt"

func PrintThis(arg string) {
    fmt.Printf("I'm printing %s", arg)
}

func PrintThisAndThat(arg1, arg2 string) {
    fmt.Printf("Now printing %s and %s", arg1, arg2)
}

func Invoke(fn interface{}, args ...string) {
    //fn(args...)
}

func main() {
    Invoke(PrintThis, "foo")
    Invoke(PrintThisAndThat, "foo", "bar")
}

This is not the actual production code, but this is a simplified version.

Question :- If I uncomment the line //fn(args...) I get a compile error prog.go:14: cannot call non-function fn (type interface {})

How do I execute the function which is received as the argument tho the Invoke() function?

What is the right way to achieve this?





Aucun commentaire:

Enregistrer un commentaire