Home > Article > Backend Development > Why Does Go Throw \"prev declared and not used\" Error Despite Variable Initialization?
Go - Error: "prev declared and not used", Despite Variable Initialization
In Go, encountering the error "prev declared and not used" when variables appear initialized can be puzzling. Let's examine a specific case:
<code class="go">package main import "fmt" 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()) } }</code>
The issue lies in the inner anonymous function within fibonacci(). The code declares a variable prev, which is shadowed by the subsequent := assignment. This creates a new local variable that is not used, triggering the "prev declared and not used" error.
Resolution:
To solve this problem, modify the := assignment to =. This assigns the value of temp to the inherited prev variable:
<code class="go">prev = temp</code>
Similarly, the next line should be:
<code class="go">curr = curr + prev</code>
This ensures that prev is properly used and the error is resolved.
The above is the detailed content of Why Does Go Throw \"prev declared and not used\" Error Despite Variable Initialization?. For more information, please follow other related articles on the PHP Chinese website!