-2

I use a pattern where a variable is declared outside of an if-block and the block determines the value to assign to it. The compiler does not like the following code and reports: "result declared but not used". It looks proper to me... Please explain what I am misunderstanding.

Thank you for your help, Mike

func blah() {
    var result error = nil // "result declared but not used"
    if 1 == 1 {
        result = fmt.Errorf("ouch")
    }
}
A Bit of Help
  • 1,368
  • 19
  • 36
  • 3
    It is accessible – that’s why there’s no error on the `result = …` line. But you haven’t used the value assigned to it. – Ry- Jul 08 '22 at 22:10
  • Arggg! Makes sense... I assumed that the result = fmt.Errorf() would account for using it. Thank you for the quick response! – A Bit of Help Jul 08 '22 at 22:11
  • 1
    You're "using it" to store a value, but you never used the stored value - assignment doesn't count as 'use'. – Grismar Jul 09 '22 at 05:15

1 Answers1

0

Assigning a value into a variable is not using that variable.
This is also an error (here compiler never read the variable so it's not used) .

var result string  // "result declared but not used"
result = "sheikh"

"Every declared variable have to be used" means compiler have to read the value of that variable and use it to perform at least one operation (arithmetic Operation or assignment Operation or Unary Operation or Relational Operation)

This is not an error,

var result int
result+=1 

This is not an error,

var result int  
result=1
if result == 1 {
}

If you want to avoid this error simply do this,

var result int 
result=1
_=result