Home > Backend Development > Golang > Why Does Go Throw \'prev declared and not used\' Error Despite Variable Initialization?

Why Does Go Throw \'prev declared and not used\' Error Despite Variable Initialization?

Mary-Kate Olsen
Release: 2024-10-31 03:37:01
Original
994 people have browsed it

Why Does Go Throw

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>
Copy after login

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>
Copy after login

Similarly, the next line should be:

<code class="go">curr = curr + prev</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template