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

2`1我想写一个装饰器来包装一个带有“之前”和“之后”命令的函数。第一个版本如下,其中装饰函数仅输出: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 ()

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


万千封印
浏览 155回答 1
1回答

吃鸡游戏

您必须声明正确的变量类型才能使其正常工作:func wrapper(f func(string), who string) { ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go