Question on closure in Go (Go and Coding beginner)

Hi all,

I’m new to Go and programming in general and I am working my way through Todd Mcleod’s Go course on udemy. I found this function here: https://golang.org/doc/play/fib.go to do the fibonacci sequence and tweaked it a bit.

Can someone explain why the below:

package main

import "fmt"

func main() {

	n := fib()

	for i := 0; i < 10; i++ {
		fmt.Println(n())
	}
}

func fib() func() int {
	a, b := 0, 1
	return func() int {
		a, b = b, a+b
		return a
	}
}

results in the below which is what I expect.

fibonacci % go run main.go

1

1

2

3

5

8

13

21

34

55 

but this:

package main

import "fmt"

func main() {

	n := fib()

	for i := 0; i < 10; i++ {
		fmt.Println(n())
	}
}

func fib() func() int {
	a, b := 0, 1
	return func() int {
		
			a = b
			b = a + b
		return a
	}
}

results in

fibonacci % go run main.go
1
2
4
8
16
32
64
128
256
512

I imagine it’s something really obvious but I’m still new at this so I’m not sure what I am missing. I appreciate the advice.

Hi @cozco, welcome!

This has nothing do do with closures but with the assignment of a and b.

This

a, b = b, a+b

assigns the old valud of b to a and the sum of the old values of a and b to b.

This

a = b
b = a + b

also assigns the old value of b to a but it assigns the sum of the new value of a and the old value of b to b. It basically ignores a and adds b to itself as in b * 2. That’s what you get.

2 Likes

Hi @lutzhorn, thank you for the clear explanation! That makes complete sense when you lay it down like that. I really do appreciate you breaking it down like that.

1 Like