如何将参数传递给装饰函数?

时间:2021-05-16 16:31:50

标签: go parameters decorator

我想写一个装饰器来用“before”和“after”命令包装一个函数。下面是第一个版本,其中装饰函数仅输出 <pre id='price' class="container"></pre>

hello

(游乐场:https://play.golang.org/p/vJuQKWpZ2h9

我现在想用一个参数(在我的例子中是 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") } )来调用装饰函数。在上面的例子中,它成功地传递给 "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)
}

将参数传递给装饰函数的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您必须声明正确的变量类型才能使其工作:

func wrapper(f func(string), who string) {
...