2`1我想寫一個裝飾器來包裝一個帶有“之前”和“之后”命令的函數(shù)。第一個版本如下,其中裝飾函數(shù)僅輸出: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)我現(xiàn)在想用參數(shù)調(diào)用修飾的函數(shù)(在我的情況下)。在上面的示例中,它已成功傳遞給,但隨后我不知道該怎么做。我以為我會只是"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 ()將參數(shù)傳遞給修飾函數(shù)的正確方法是什么?
- 1 回答
- 0 關(guān)注
- 95 瀏覽
添加回答
舉報
0/150
提交
取消