Go语言中的函数,有人可以帮我解释一下吗?

huangapple go评论67阅读模式
英文:

Functions in go lang, can someone please break this down for me?

问题

这段代码是一个用于生成斐波那契数列的闭包函数。让我来解释一下这段代码的具体含义。

首先,makeFibGen 函数返回了一个匿名函数,这个匿名函数也是一个闭包函数。闭包函数可以访问并修改其外部函数中定义的变量。

在闭包函数内部,有两个变量 f1f2,它们分别表示斐波那契数列中的前两个数。

每次调用闭包函数时,它会计算下一个斐波那契数,并更新 f1f2 的值。这是通过以下这行代码实现的:

f2, f1 = (f1 + f2), f2

这行代码使用了多重赋值和元组拆包的特性。首先,(f1 + f2) 表示当前斐波那契数列的下一个数,然后将这个值同时赋给 f2f1。这样,f2 就变成了下一个数,而 f1 则变成了当前数。

最后,闭包函数返回 f1,也就是当前的斐波那契数。

通过这种方式,每次调用闭包函数,都会生成斐波那契数列中的下一个数。

英文:

I was taking the tour of golang when I stumbled upon closures, one thing led to another and I landed at https://www.calhoun.io/5-useful-ways-to-use-closures-in-go/

Here I was stumped by the code snippet

func makeFibGen() func() int {
  f1 := 0
  f2 := 1
  return func() int {
    f2, f1 = (f1 + f2), f2
    return f1
  }
}

Can someone please break this down to me and explain what exactly is going on?
Especially this line:

f2, f1 = (f1 + f2), f2

答案1

得分: 4

f2被赋值为f1 + f2,同时f1被赋值为(原始值的)f2。所以如果f1, f2之前是3, 5,那么之后它们将变为5, 85, (3 + 5))。

这样,我们得到了一个斐波那契数列生成器,因为每次调用内部函数时,前两个值的和被返回并保存下来,与前两个数中较大的那个一起用于构建下一对数,当它们相加时将产生下一个斐波那契数,以此类推。

英文:

f2 is assigned f1 + f2 while at the same time f1 is assigned (the original value of) f2. So if f1, f2 were 3, 5 before, they would be 5, 8 (5, (3 + 5)) afterwards.

This way, we get a Fibonacci generator, because every time the inner function is called, the sum of the previous two values gets returned and saved for next time together with the larger one of the previous numbers, building the next pair that when added together will produce the next Fibonacci number, and so on.

huangapple
  • 本文由 发表于 2021年10月20日 07:42:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/69638743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定