如何将参数传递给装饰函数?
How to pass parameters to decorated functions?
我想编写一个装饰器来用“之前”和“之后”命令包装一个函数。第一个版本如下,装饰函数只输出 hello
:
package main
import "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 main
import "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 ()
向装饰函数传递参数的正确方法是什么?
您必须声明正确的变量类型才能工作:
func wrapper(f func(string), who string) {
...
我想编写一个装饰器来用“之前”和“之后”命令包装一个函数。第一个版本如下,装饰函数只输出 hello
:
package main
import "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 main
import "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 ()
向装饰函数传递参数的正确方法是什么?
您必须声明正确的变量类型才能工作:
func wrapper(f func(string), who string) {
...