简体   繁体   English

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

[英]How to pass parameters to decorated functions?

I would like to write a decorator to wrap a function with "before" and "after" commands.我想编写一个装饰器来用“之前”和“之后”命令包装 function。 A first version is below, where the decorated function just outputs hello :下面是第一个版本,其中装饰的 function 仅输出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")
}

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

I now would like to call the decorated function with a parameter (in my case "world" ).我现在想用一个参数(在我的例子中是"world" )调用装饰的 function 。 In the example above, it is successfully passed to wrapper() but then I do not know what to do further.在上面的示例中,它已成功传递给wrapper()但我不知道该怎么做。 I thought that I would just我以为我会

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)
}

The compilation failes with编译失败

.\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 ()

What is the proper way to pass arguments to the decorated function?将 arguments 传递给装饰的 function 的正确方法是什么?

You have to declare the correct variable type for this to work:您必须声明正确的变量类型才能使其工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM