Not used var error

88 views
Skip to first unread message

Paulo Júnior

unread,
Jan 17, 2022, 10:07:10 PM1/17/22
to golang-nuts
Hi all.

I'm studying about if statement and comma ok construction and I'm not sure why the piece of code (https://go.dev/play/p/ScFJsih6lwR) bellow does not work. The compiler says that: x declared but not used. However, x is used in the second if statement of the main function, as you can see.

It is worthy to notice that  x is just assigned (not declared) in the first if of the main function, because I declared it as follows: var x int  

func MyFunc() (int, bool) {
        return 1, true
}

func main() {
        var x int
        if x, ok := MyFunc(); !ok {
                fmt.Println("Err")
        }
        fmt.Println(x)
}

Thank you and best regards,
Paulo.

Ian Lance Taylor

unread,
Jan 17, 2022, 10:18:27 PM1/17/22
to Paulo Júnior, golang-nuts
When you write "if x, ok := ... { }" that declares a new variable "x"
(and a new variable "ok") that are only visible in the if statement.
The "x" declared in the if statement shadows the "x" declared in "var
x int". That is, there are two different variables named "x" here.
The one declared in the "if" statement is not used.

It looks like you may want to write something like

var x int
var ok bool
if x, ok = MyFunc(); !ok {
fmt.Println("Err")
}
fmt.Println(x)

Note the use of "=" rather than ":=" in the if statement.

Ian

Paulo Júnior

unread,
Jan 18, 2022, 4:36:08 AM1/18/22
to Ian Lance Taylor, golang-nuts
Dear, Ian. 

You are correct and I was wondering why the reassignment did not work in the case of x var. I found the answer in the Effective Go documentation, in the Redeclaration and reassignment section:

In a := declaration a variable v may appear even if it has already been declared, provided:
  • this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §),
Thanks for your help.

Best regards.
Paulo.
Reply all
Reply to author
Forward
0 new messages