Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go — declared and not used error, when I think I have done so to the variable

Tags:

go

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

like image 880
Matthew H Avatar asked Feb 16 '13 00:02

Matthew H


People also ask

What is declared and not used error in Go language?

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.

How to fix “I have declared a variable but not used it?

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.

Why was I not declared in this scope?

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.

Why is there no compiler option for error handling in go?

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.


1 Answers

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 :=.

like image 135
Lily Ballard Avatar answered Sep 22 '22 11:09

Lily Ballard