将闭包作为函数的参数传递

时间:2019-06-19 05:34:00

标签: go closures

在此示例中:https://gobyexample.com/closures 如果我们更改:

    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())

    fmt.Println(intSeq())
    fmt.Println(intSeq())
    fmt.Println(intSeq())

go run将失败,并显示错误:./prog.go:32:5: Println arg intSeq() is a func value, not called

但是从此示例:https://gobyexample.com/recursion

    fmt.Println(fact(7))

我们可以将fact(7)函数用作fmt.Println的参数。为什么我们有区别?

1 个答案:

答案 0 :(得分:1)

估计。 当您在代码中运行Golang游乐场或任何测试时,go vet首先运行,如果返回错误,则实际的go代码不会运行。

如果您go buildgo run(已通过1.12.5测试),则代码可以正常运行,并打印函数指针地址。

如果将代码复制到教程站点,例如,这里https://tour.golang.org/welcome/1。代码按预期工作。

相关问题