8

What's wrong with this code?

package main import "fmt" // fibonacci is a function that returns // a function that returns an int. func fibonacci() func() int { prev := 0 curr := 1 return func() int { temp := curr curr := curr + prev prev := temp return curr } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } } 

prog.go:13: prev declared and not used

1
  • 2
    Instead of “what’s wrong with this code” you probably meant to ask (more specifically) “why does this code produce this compiler error”, right? Please be as specific as possible when asking questions in the future. :) Commented Feb 16, 2013 at 13:19

2 Answers 2

16

You declared a variable named prev and then never used it.

Specifically, you said prev := temp. This is creating a new local variable in the current scope named prev. I assume you meant to just say prev = temp, which modifies the prev variable inherited from the surrounding scope. Similarly you probably meant to say curr = curr + prev on the previous line, instead of using :=.

Sign up to request clarification or add additional context in comments.

2 Comments

To elaborate, = assigns the right to the left, and := creates a new variable named the left, and assigns it the value of the item on the right.
Thanks! Makes perfect sense.
3

If you make the changes suggested by Kevin Ballard, then,

package main import "fmt" // fibonacci is a function that returns // a function that returns an int. func fibonacci() func() int { prev := 0 curr := 1 return func() int { temp := curr curr = curr + prev prev = temp return curr } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } } 

Output:

1 2 3 5 8 13 21 34 55 89 

The output is not the Fibonacci sequence.

For the Fibonacci sequence,

package main import "fmt" func fibonacci() func() int { a, b := 0, 1 return func() (f int) { f, a, b = a, b, a+b return } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } } 

Output:

0 1 1 2 3 5 8 13 21 34 

3 Comments

To add a tiny bit, you can also replace curr = curr + prev with just curr += prev. There's no functional difference, of course - just slightly fewer keystrokes.
Although you fixed the code and provided a program code suggestion for the seemingly wanted functionality of the program, you did not answer the actual question *what is wrong with the code*/“why does it produce that compiler error”. That’s why I will still down-vote it, even though it may be useful in a wider scope (which does not really fit this Q/A format).
I agree, and it was actually my intention to leave off the first two numbers of the sequence; I was just wanting to test closures. Still, this may be helpful to some readers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.