"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why am I getting the \"prev declared and not used\" error in my Go code?

Why am I getting the \"prev declared and not used\" error in my Go code?

Published on 2024-11-08
Browse:849

Why am I getting the \

Go - Declared Variable Name prev is Unused in Given Function Scope

In the following code snippet, the error message "prog.go:13: prev declared and not used" is displayed.

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 

The error occurs because the variable prev is declared in the function fibonacci, but it is never used. Specifically, the line prev := temp creates a new local variable named prev. This variable is different from the prev variable declared in the outer scope. To fix the error, we need to modify the code to use the prev variable from the outer scope instead of creating a new local variable.

Here is the corrected 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 
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3