Main question is "is it possible to pass any type func as param and how?". I am learning Go and want to make my own async wrap function like this:
func AsyncFunc(fn func(), args ...interface{}) chan bool {
var done chan bool;
go func() {
fn(args...);
done <- true;
}();
return done;
}
and call it:
max := func(a, b int) int {
//some hard code what will be goroutine
if a > b {return a};
return b;
}
done := AsyncFunc(max, 5, 8);
//some pretty code
<- done;
P.S. sorry for my English if it is bad...
Edit1: I know it is useless, slow and danger. It is just my crazy idea what i want just realise.
i found the way to do what i want.
package main
import (
"fmt"
)
func t1(t int) {
fmt.Printf("%d
", t);
}
func t2(t string) {
fmt.Printf("%s
", t);
}
func test(fn interface{}, data interface{}) {
switch fn.(type) {
case func(string):
fn.(func(string))(data.(string))
case func(int):
fn.(func(int))(data.(int))
}
}
func main() {
test(t1, 123);
test(t2, "test");
}
Of cause go can do it, please consider the following simple example:
package main
import (
"fmt"
)
type funcDef func(string) string
func foo(s string) string {
return fmt.Sprintf("from foo: %s", s)
}
func test(someFunc funcDef, s string) string {
return someFunc(s)
}
func main() {
output := test(foo, "some string")
fmt.Println(output)
}
And to be spefic in your case, you just need to
type funcDef func(int, int) int
func AsyncFunc(func funcDef, a, b int) chan bool {
....
}
done := AsyncFunc(max, 5, 8)