golang 将 func 作为参数传递给另一个 func

golang passing func as param to another func

主要问题是"is it possible to pass any type func as param and how?"。 我正在学习 Go 并且想像这样制作我自己的异步包装函数:

func AsyncFunc(fn func(), args ...interface{}) chan bool {
    var done chan bool;

    go func() {
        fn(args...);
        done <- true;
    }();

    return done;
}

并称它为:

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。抱歉我的英语不好...

编辑1: 我知道这是无用的、缓慢的和危险的。这只是我想要实现的疯狂想法。

Go当然可以。请考虑以下简单示例:

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)
}

具体到你的情况,你只需要:

type funcDef func(int, int) int

func AsyncFunc(func funcDef, a, b int) chan bool {
    ....
}

done := AsyncFunc(max, 5, 8)

我找到了做我想做的事情的方法。

 package main


 import (
     "fmt"
 )


 func t1(t int) {
     fmt.Printf("%d\n", t);
 }


 func t2(t string) {
     fmt.Printf("%s\n", 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");
 }