On Sun, Jan 28, 2018 at 12:53 AM, Wenbin Shang <wbsh...@gmail.com> wrote:
>
> The following code:
>
> package main
>
> import "fmt"
>
> func main() {
>     var i int
>     fmt.Println(i)
>     if true {
>         i = 5
>         i, j := 3, 4
>         fmt.Println(i, j)
>     }
>     fmt.Println(i)
> }
>
> Output:
> 0
> 3 4
> 5
>
> Is this a reasonable behavior? I intuitively thought only j is declared in
> if block and i will be the same as outer one.

This is indeed how the language works.  The scope of a variable begins
at the point at which it is declared.  So the `i, j := 3, 4` in the
inner block is the start of the scope of the inner i.  The `i = 5`
appears before that scope, and therefore refers to the i in the outer
block.

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.
For more options, visit https://groups.google.com/d/optout.

Reply via email to