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.

Em ter, 18 de jan de 2022 00:17, Ian Lance Taylor <i...@golang.org>
escreveu:

> On Mon, Jan 17, 2022 at 7:07 PM Paulo Júnior <pauloafpjun...@gmail.com>
> wrote:
> >
> > 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)
> > }
>
> 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
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CACtisV4kP-OVB60gNr3Spyhm9iys5o_upFM-eX-XkRHMxn6-nA%40mail.gmail.com.

Reply via email to