猿问

需要更多关于 Go 的函数闭包的评论

下面是A Tour of Go中函数闭包的代码,我对函数闭包有一点了解,但我是Go的初学者。


package main


import "fmt"


func adder() func(int) int {

    sum := 0

    return func(x int) int {

        sum += x

        return sum

    }

}


func main() {

    pos, neg := adder(), adder()

    for i := 0; i < 10; i++ {

        fmt.Println(

            pos(i),

            neg(-2*i),

        )

    }

}

以下是一些问题:

  1. 分别是[参数列表][return_types]func adder() func(int) int {

  2. 对于与问题.1相同的行,为什么有(int)而不是像(x int)这样的东西?

  3. 对于 ,这是否意味着将函数加法器分配给 pos 和 neg,为什么不应该是?pos, neg := adder(), adder()pos, neg := adder, adder


qq_笑_17
浏览 76回答 1
1回答

喵喔喔

问:对于 func adder() func(int) int { 分别是 [参数列表] 和 [return_types] 是什么?答:在这里,我们有一个名为函数的函数,它不带任何参数,该函数返回一个函数,该函数采用一个整数并返回一个整数。adder()func(int) int问:对于与 Question.1 相同的行,为什么有 (int),而不是类似 (x int) 的东西?答:这是功能adder()func adder() func(int) int {&nbsp; &nbsp; sum := 0&nbsp; &nbsp; return func(x int) int {&nbsp; &nbsp; &nbsp; &nbsp; sum += x&nbsp; &nbsp; &nbsp; &nbsp; return sum&nbsp; &nbsp; }}看看正在返回的函数,这里已经有一个命名参数(),所以我们不需要在 中再次提到它,因为如果我们做这样的事情,这里没有用。func(x int) intxfunc adder() func(int) intfunc adder() func(x int) intx因此,如果返回的函数具有 2 个参数(其中一个额外的参数是类型),则它类似于以下代码:stringfunc adder() func(int, string) int {&nbsp; &nbsp; sum := 0&nbsp; &nbsp; return func(x int, y string) int {&nbsp; &nbsp; &nbsp; &nbsp; sum += x&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(y)&nbsp; &nbsp; &nbsp; &nbsp; return sum&nbsp; &nbsp; }}请注意,我们在 处添加了一个类型,这是因为我们返回的函数采用类型。stringfunc adder() func(int, string) int {string问:对于 pos, neg := adder(), adder(), 这是否意味着将函数 adder 分配给 pos 和 neg,为什么不应该是 pos, neg := adder, adder?答:看,当我们赋值给()时,就变成了一个新的函数,因为返回了一个函数,这样我们就可以做到了。posadder()pos := adder()posadder()func(int) intpos(i)同样适用于 .neg
随时随地看视频慕课网APP

相关分类

Go
我要回答