</bugz loading .

declared but not used golang error fix in 1 minute

In this tutorial you are going to know the solution for the declared but not used error in golang / go

Probability 1 : Variable declared and not used anywhere

It means that you have declared a variable in the code but did not used it anywhere. This makes the code crash because go wants you to write clean code which is easy to understand and use every variable you declare.

Ignoring unused variable

If you want to ignore this error you can comment that declaration part of the code or use a blank identifier _ as shown below.

        package main

func main(){
    str := "bugz"
    _ = str // using blank identifier
}
      

Probability 2 : Variable declared and used yet the code crashes

        package main

import "fmt"

func main(){

    var str string

    if false {
        str := "bugz"
    }else{
        str := "new bugz"
    }

    fmt.Println(str) // variable used
}
      

In the code above, the variable str is used yet the code crashes with the same error.

It returnes the error because, in the if-else block of the code, the variable str is being re-declared. In go, any variables declared in the if-else blocks are local which means that the variables can be used only in the block range ( in the if-else block ).

As in the block range the variable is not being used, the code crashes.

Solution

As you are re-declaring & not using the str variables , the code is crashing. To solve this problem, you just need to assign new values to the global variable str instead of declaring them again, as shown below.

        var str string // global variable

if false {
    str = "bugz" // assigning "bugz" to str
}else{
    str = "new bugz" // assigning "new bugz" to str
}
      

Declaring vs Assigning

        str := "bugz" // declaring. ":="

str = "bugz" // assigning. "="
      

Thank you for reading, happy coding ✌🏾