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

Patricia Arquette
Release: 2024-10-31 12:47:31
Original
729 people have browsed it

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.

<code class="go">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())
    }
}</code>
Copy after login

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:

<code class="go">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())
    }
}</code>
Copy after login

The above is the detailed content of Why am I getting the \'prev declared and not used\' error in my Go code?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!