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.