简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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