When encountering a "declared and not used" error in Go, programmers may assume they have already initialized a variable within their code. However, as illustrated below, the root cause may lie in the premature declaration of variables.
Consider the following code snippet:
<code class="go">package main import "fmt" // fibonacci is a function that returns // a function that returns an int. func fibonacci() func() int { var prev int // Declare a variable named prev var curr = 1 // Initialize curr with the value 1 return func() int { var temp = curr // Declare a variable named temp curr := curr + prev // Assign curr to the sum of curr and prev prev := temp // Assign prev to the value of temp return curr } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } }</code>
This code is designed to generate a sequence of Fibonacci numbers. However, we encounter an error stating "prog.go:13: prev declared and not used."
To resolve this error, we need to understand the difference between variable declaration and initialization. In this code, we declare a variable named prev with the line var prev int, indicating that it will hold an integer value. However, we don't initialize it with an actual value. The assignment prev := temp, which occurs later in the code, creates a new local variable named prev within the current scope, shadowing the outer prev variable. Consequently, the original prev variable remains uninitialized.
To rectify this issue, we can replace the declaration prev := temp with an assignment prev = temp, which modifies the prev variable inherited from the surrounding scope. Additionally, we should revise the assignment curr := curr prev on the previous line to use = instead of :=, ensuring proper variable assignment. The corrected code is shown below:
<code class="go">package main import "fmt" // fibonacci is a function that returns // a function that returns an int. func fibonacci() func() int { var prev, curr int // Declare and initialize prev and curr within the function scope return func() int { var temp = curr curr = curr + prev prev = temp return curr } } func main() { f := fibonacci() for i := 0; i < 10; i++ { fmt.Println(f()) } }</code>
This corrected code eliminates the premature declaration of prev and ensures proper variable initialization, resolving the "declared and not used" error.
The above is the detailed content of Why does Go throw a \'declared and not used\' error even when a variable appears to be initialized?. For more information, please follow other related articles on the PHP Chinese website!