"I intuitively thought only j is declared in if block and i will be the 
same as outer one."

The compiler knows nothing about your intuition! It follows The Go 
Programming Language Specification https://golang.org/ref/spec

Short variable declarations 
https://golang.org/ref/spec#Short_variable_declarations

Unlike regular variable declarations, a short variable declaration may 
redeclare variables provided they were originally  (or the parameter lists 
if the block is the function body) with the same type, and at least one of 
the non-blank variables is new. As a consequence, redeclaration can only 
appear in a multi-variable short declaration. Redeclaration does not 
introduce a new variable; it just assigns a new value to the original. 

In your case, the variable i is not declared earlier in the same block, 
it's declared in the outer block. Therefore, in the short variable 
declaration, the variable i is declared, it's not redeclared. 

Peter

On Sunday, January 28, 2018 at 12:31:48 PM UTC-5, Wenbin Shang 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.
>

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

Reply via email to