Home > Software engineering >  Functions in go lang, can someone please break this down for me?
Functions in go lang, can someone please break this down for me?

Time:10-21

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

CodePudding user response:

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.

  • Related