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
In the Go programming language, if any variable is declared and not used in the code – then the compiler displays the error "declared and not used". For good programming practice, we have to remove those unused variables or unused packages from the code. It will save the memory and compilation, execution time.
As the error itself suggests, you have declared a variable but not used it. The below snippet would result in the error. The fix is to actually use this variable somewhere or just get rid of it.
I was not declared in this scope because I'm trying to use I outside of I scopes I scope is limited to those curly braces. Now let's say I added an if statement in here. (upbeat music) So now you can see I'm using I, which was created in the for-loop inside of this nested if statement.
Such an option has not been added, though, because compiler options should not affect the semantics of the language and because the Go compiler does not report warnings, only errors that prevent compilation. There are two reasons for having no warnings. First, if it's worth complaining about, it's worth fixing in the code.
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 :=
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With