ker*_*azi 2 parameters func go
主要问题是“是否可以将任何类型的 func 作为参数以及如何传递?”。我正在学习 Go 并希望像这样制作我自己的异步包装函数:
func AsyncFunc(fn func(), args ...interface{}) chan bool {
var done chan bool;
go func() {
fn(args...);
done <- true;
}();
return done;
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
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;
Run Code Online (Sandbox Code Playgroud)
PS如果我的英语不好,对不起...
Edit1:我知道它是无用的、缓慢的和危险的。这只是我想要实现的疯狂想法。
小智 6
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)
}
Run Code Online (Sandbox Code Playgroud)
具体到您的情况,您只需要:
type funcDef func(int, int) int
func AsyncFunc(func funcDef, a, b int) chan bool {
....
}
done := AsyncFunc(max, 5, 8)
Run Code Online (Sandbox Code Playgroud)