2`1我想写一个装饰器来包装一个带有“之前”和“之后”命令的函数。第一个版本如下,其中装饰函数仅输出:hellopackage mainimport "fmt"func main() { wrapper(printHello, "world")}func wrapper(f func(), who string) { fmt.Printf("before function, sending %v\n", who) f() fmt.Print("after function\n")}func printHello() { fmt.Printf("hello\n")}(游乐场:https://play.golang.org/p/vJuQKWpZ2h9)我现在想用参数调用修饰的函数(在我的情况下)。在上面的示例中,它已成功传递给,但随后我不知道该怎么做。我以为我会只是"world"wrapper()package mainimport "fmt"func main() { wrapper(printHello, "world") // cannot use printHello as the type func()}func wrapper(f func(), who string) { fmt.Printf("before function, sending %v\n", who) f(who) // too many arguments fmt.Print("after function\n")}func printHello(who string) { fmt.Printf("hello %v\n", who)}编译失败.\scratch_11.go:6:9: cannot use printHello (type func(string)) as type func() in argument to wrapper.\scratch_11.go:11:3: too many arguments in call to f have (string) want ()将参数传递给修饰函数的正确方法是什么?
- 1 回答
- 0 关注
- 69 浏览
添加回答
举报
0/150
提交
取消